Previous: [MySQL Must Know and Know (9)] [Summary Data]
+++++++++++++Start line++++++++++++++++
Article Directory
1. Data grouping
Returns the number of products provided by supplier 1003
mysql> SELECT COUNT(*) AS num_prods
-> FROM products
-> WHERE vend_id =1003;
Two, create a group
mysql> SELECT vend_id, COUNT(*) AS num_prods
-> FROM products
-> GROUP BY vend_id;
Regarding the provisions of GROUP BY 1. The
GROUP BY clause can contain any number of columns
. 2. Groups are nested in the GROUP BY clause, and the data will be summarized on the last specified group. 3. The GROUP BY clause is
listed in the sentence Each column of must be a retrieval column or a valid expression
4. Except for aggregate calculation statements, each column in the SELECT statement must be given in the GROUP BY clause
5. If the grouping has a NULL value, then NULL Will be returned as a group.
6. The GROUP BY clause must appear after the WHERE clause and before the ORDER BY clause
Three, filter group
HAVING supports all WHERE operators
The conditions and options of the WHERE clause are applicable to HAVING, the syntax is the same, the keywords are different
mysql> SELECT cust_id, COUNT(*) AS orders
-> FROM orders
-> GROUP BY cust_id
-> HAVING COUNT(*) >= 2;
Difference between HAVING and WHERE
WHERE filters before data grouping, HAVING filters after data grouping
List suppliers with more than two products with a price of 10 or more
mysql> SELECT vend_id, COUNT(*) AS num_prods
-> FROM products
-> WHERE prod_price >= 10
-> GROUP BY vend_id
-> HAVING COUNT(*) >= 2;
mysql> SELECT vend_id,COUNT(*) AS num_prods
-> FROM products
-> GROUP BY vend_id
-> HAVING COUNT(*) >= 2;
Four, grouping and sorting
Retrieve the order number and total order price of orders whose total order price is greater than or equal to 50
mysql> SELECT order_num, SUM(quantity*item_price) AS ordertotal
-> FROM orderitems
-> GROUP BY order_num
-> HAVING SUM(quantity*item_price) >= 50;
Sort output by total order price
mysql> SELECT order_num, SUM(quantity*item_price) AS ordertotal
-> FROM orderitems
-> GROUP BY order_num
-> HAVING SUM(quantity*item_price) >= 50
-> ORDER BY ordertotal;
Five, SELECT clause order
SELECT-FROM-WHERE-GROUP BY (group description)-HAVING (group-level filtering)-ORDER BY-LIMIT
+++++++++++++End line++++++++++++++++