Grouping Data From Tables In SQL
The concept of grouping
From sale_order_details table, we well create a set containing several sets of rows groups together based on a condition.
Table name: sales_order_details
S Order No.
Product Qty Ordered
Qty. Ordered
Qty. Disp
019001
P00001
10
10
019001
P03453
3
3
019001
P06734
3
3
046865
P06734
4
4
046865
P03453
10
10
046865
P03453
2
2
073965
P00001
1
1
073965
P06734
1
1
Example
Select product_no, total qty_ordered for each product;
SELECT Product_no, sum(qty_ordered) “Total Qty Ordered”
FROM slaes_order _details
GROUP BY product_no;
The following is the output displayed:
Product No. Total Qty. Ordered
------------------ ---------------------------
P00001 13
P03453 15
P06734 8
A condition cab be imposed on the group by clause, using the having clause as done in the following example:
1. Select product_no, total qty_ordered for products ’P00001’ OR ‘P03454’,
Select product_no, sum(qty_ordered)”Total Qty Ordered”
FROM sales_order_details
GROUP BY product_no
HAVING product_no=’P00001’ OR ‘P03454’,
The following output displayed:
Product No. Total Qty Ordered
---------------- -------------------------
P00001 13
P03453 15
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment