Tuesday, 15 November 2011

SQL GROUP BY

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

Syntax 

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name 



The "Custmast" table 


custcode
custname
city
qty
rate
1
Siva
Srivilliputtur
50
70
2
Bala
Sivakasi
30
56
3
Kanna
Madurai
100
200
4
Vijay
Chennai
30
30
5
Kodee
Sandnes
60
80
5
Kodee
Srivilliputtur
60
30


Example :


Now we want to find the total sum (Qty) of each customer.

Select Custname,Sum(Qty)  as Tot From Custmast 
Group by CustName

custname
Tot
Siva
50
Bala
30
Kanna
100
Vijay
30
Kodee
120


Group By More than One Column

SELECT Custname,City,SUM(Qty) as Tot FROM Orders
GROUP BY
Custname,City



No comments:

Post a Comment


”Back