-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path02-aggregations.php
More file actions
241 lines (212 loc) · 7.67 KB
/
02-aggregations.php
File metadata and controls
241 lines (212 loc) · 7.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
<?php
/**
* Example: Aggregations and GROUP BY
*
* Demonstrates GROUP BY, HAVING, and aggregate functions
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\helpers\Db;
$db = createExampleDb();
$driver = getCurrentDriver($db);
echo "=== Aggregations Example (on $driver) ===\n\n";
// Setup
recreateTable($db, 'sales', [
'id' => 'INTEGER PRIMARY KEY AUTOINCREMENT',
'product' => 'TEXT',
'category' => 'TEXT',
'amount' => 'REAL',
'quantity' => 'INTEGER',
'region' => 'TEXT',
'sale_date' => 'DATE'
]);
$db->find()->table('sales')->insertMulti([
['product' => 'Laptop', 'category' => 'Electronics', 'amount' => 999.99, 'quantity' => 2, 'region' => 'East', 'sale_date' => '2025-10-01'],
['product' => 'Mouse', 'category' => 'Electronics', 'amount' => 29.99, 'quantity' => 5, 'region' => 'East', 'sale_date' => '2025-10-01'],
['product' => 'Desk', 'category' => 'Furniture', 'amount' => 299.99, 'quantity' => 1, 'region' => 'West', 'sale_date' => '2025-10-02'],
['product' => 'Chair', 'category' => 'Furniture', 'amount' => 199.99, 'quantity' => 3, 'region' => 'West', 'sale_date' => '2025-10-02'],
['product' => 'Keyboard', 'category' => 'Electronics', 'amount' => 79.99, 'quantity' => 4, 'region' => 'East', 'sale_date' => '2025-10-03'],
['product' => 'Monitor', 'category' => 'Electronics', 'amount' => 299.99, 'quantity' => 2, 'region' => 'West', 'sale_date' => '2025-10-03'],
]);
echo "✓ Inserted 6 sales records\n\n";
// Example 1: COUNT
echo "1. COUNT - Sales by category...\n";
$byCategory = $db->find()
->from('sales')
->select([
'category',
'sale_count' => Db::count()
])
->groupBy('category')
->get();
foreach ($byCategory as $row) {
echo " • {$row['category']}: {$row['sale_count']} sales\n";
}
echo "\n";
// Example 2: SUM
echo "2. SUM - Total revenue by category...\n";
$revenue = $db->find()
->from('sales')
->select([
'category',
'total_revenue' => Db::sum('amount')
])
->groupBy('category')
->orderBy(Db::sum('amount'), 'DESC')
->get();
foreach ($revenue as $row) {
echo " • {$row['category']}: \$" . number_format($row['total_revenue'], 2) . "\n";
}
echo "\n";
// Example 3: AVG
echo "3. AVG - Average sale amount by region...\n";
$avgByRegion = $db->find()
->from('sales')
->select([
'region',
'avg_amount' => Db::avg('amount')
])
->groupBy('region')
->get();
foreach ($avgByRegion as $row) {
echo " • {$row['region']}: \$" . number_format($row['avg_amount'], 2) . " average\n";
}
echo "\n";
// Example 4: MIN and MAX
echo "4. MIN/MAX - Price range by category...\n";
$priceRange = $db->find()
->from('sales')
->select([
'category',
'min_price' => Db::min('amount'),
'max_price' => Db::max('amount')
])
->groupBy('category')
->get();
foreach ($priceRange as $row) {
echo " • {$row['category']}: \$" . number_format($row['min_price'], 2) . " - \$" . number_format($row['max_price'], 2) . "\n";
}
echo "\n";
// Example 5: Multiple aggregates
echo "5. Complete statistics by category...\n";
$stats = $db->find()
->from('sales')
->select([
'category',
'total_sales' => Db::count(),
'total_quantity' => Db::sum('quantity'),
'total_revenue' => Db::sum('amount'),
'avg_sale' => Db::avg('amount'),
'min_sale' => Db::min('amount'),
'max_sale' => Db::max('amount')
])
->groupBy('category')
->get();
foreach ($stats as $row) {
echo " {$row['category']}:\n";
echo " Sales: {$row['total_sales']}\n";
echo " Units: {$row['total_quantity']}\n";
echo " Revenue: \$" . number_format($row['total_revenue'], 2) . "\n";
echo " Average: \$" . number_format($row['avg_sale'], 2) . "\n";
echo " Range: \$" . number_format($row['min_sale'], 2) . " - \$" . number_format($row['max_sale'], 2) . "\n\n";
}
// Example 6: HAVING clause
echo "6. HAVING - Categories with total revenue > $1000...\n";
$highRevenue = $db->find()
->from('sales')
->select([
'category',
'total_revenue' => Db::sum('amount')
])
->groupBy('category')
->having(Db::sum('amount'), 1000, '>')
->get();
foreach ($highRevenue as $row) {
echo " • {$row['category']}: \$" . number_format($row['total_revenue'], 2) . "\n";
}
echo "\n";
// Example 7: Multiple GROUP BY columns
echo "7. GROUP BY multiple columns (category + region)...\n";
$detailed = $db->find()
->from('sales')
->select([
'category',
'region',
'sales' => Db::count(),
'revenue' => Db::sum('amount')
])
->groupBy(['category', 'region'])
->orderBy('category')
->orderBy('region')
->get();
foreach ($detailed as $row) {
echo " • {$row['category']} ({$row['region']}): {$row['sales']} sales, \$" . number_format($row['revenue'], 2) . "\n";
}
echo "\n";
// Example 7b: GROUP_CONCAT / STRING_AGG
echo "7b. GROUP_CONCAT / STRING_AGG - Products by category...\n";
$concat = $db->find()
->from('sales')
->select([
'category',
// SQLite DISTINCT in GROUP_CONCAT may not be available in older versions
'products' => ($driver === 'sqlite')
? Db::groupConcat('product', ', ', false)
: Db::groupConcat('product', ', ', true)
])
->groupBy('category')
->orderBy('category')
->get();
foreach ($concat as $row) {
echo " • {$row['category']}: {$row['products']}\n";
}
echo "\n";
// Example 8: FILTER clause - Conditional aggregates
echo "8. FILTER clause - Separate aggregates for North and South...\n";
$filtered = $db->find()
->from('sales')
->select([
'category',
'total_sales' => Db::count('*'),
'north_sales' => Db::count('*')->filter('region', 'North'),
'south_sales' => Db::count('*')->filter('region', 'South'),
'total_revenue' => Db::sum('amount'),
'north_revenue' => Db::sum('amount')->filter('region', 'North'),
'south_revenue' => Db::sum('amount')->filter('region', 'South'),
])
->groupBy('category')
->orderBy('category')
->get();
echo " Category breakdown by region:\n";
foreach ($filtered as $row) {
echo " • {$row['category']}:\n";
echo " Total: {$row['total_sales']} sales, \$" . number_format($row['total_revenue'], 2) . "\n";
echo " North: {$row['north_sales']} sales, \$" . number_format($row['north_revenue'], 2) . "\n";
echo " South: {$row['south_sales']} sales, \$" . number_format($row['south_revenue'], 2) . "\n";
}
echo "\n";
// Example 9: FILTER with multiple conditions
echo "9. FILTER - High-value sales (> $200)...\n";
$highValue = $db->find()
->from('sales')
->select([
'region',
'all_sales' => Db::count('*'),
'high_value_sales' => Db::count('*')->filter('amount', 200, '>'),
'high_value_total' => Db::sum('amount')->filter('amount', 200, '>'),
])
->groupBy('region')
->orderBy('region')
->get();
foreach ($highValue as $row) {
$highValueTotal = $row['high_value_total'] ?? 0;
echo " • {$row['region']}: {$row['high_value_sales']}/{$row['all_sales']} high-value sales, \$" . number_format($highValueTotal, 2) . "\n";
}
echo "\nAggregations example completed!\n";
echo "\nKey Takeaways:\n";
echo " • Use aggregate functions: COUNT, SUM, AVG, MIN, MAX\n";
echo " • GROUP BY groups rows by column values\n";
echo " • HAVING filters grouped results (like WHERE for groups)\n";
echo " • Can group by multiple columns\n";
echo " • FILTER clause allows conditional aggregation without subqueries\n";
echo " • FILTER works with all aggregate functions (COUNT, SUM, AVG, etc.)\n";