MySQL aggregation query
MySQL supports multiple aggregation queries, including SUM, COUNT, AVG, MIN, MAX, and more.
The following is an example table structure and sample data:
Table name: orders
|Order_ ID | customer_ Id | order_ Date | amount|
|----------|-------------|------------|--------|
|1 | 1 | 2022-01-01 | 100|
|2 | 1 | 2022-01-02 | 200|
|3 | 2 | 2022-01-01 | 150|
|4 | 2 | 2022-01-02 | 300|
1. SUM aggregation query: calculating the sum of a certain column
sql
SELECT SUM(amount) as total_amount
FROM orders;
Result: total_ Amount=750
2. COUNT aggregation query: calculating the number of a column
sql
SELECT COUNT(order_id) as total_orders
FROM orders;
Result: total_ Orders=4
3. AVG aggregation query: calculating the average value of a column
sql
SELECT AVG(amount) as avg_amount
FROM orders;
Result: avg_ Amount=187.5
4. MIN aggregation query: finding the minimum value of a certain column
sql
SELECT MIN(amount) as min_amount
FROM orders;
Result: min_ Amount=100
5. MAX aggregation query: Find the maximum value of a column
sql
SELECT MAX(amount) as max_amount
FROM orders;
Result: max_ Amount=300
In addition to the basic aggregation queries mentioned above, MySQL also supports other advanced aggregation queries, such as GROUP BY, HAVING, etc., which can be used for grouping, filtering, and other operations on data. Here is an example:
sql
SELECT customer_id, SUM(amount) as total_amount
FROM orders
GROUP BY customer_id
HAVING total_amount > 200;
Result:
|Customer_ Id | total_ Amount|
|-------------|--------------|
|1 | 300|
|2 | 450|
In this example, first press customer on the orders table_ The ID is grouped, and the total amount in each group is calculated, and groups with a total greater than 200 are filtered out.