SQL

SQL Server GroupBy and Having clause

Group by classifies identical data into groups. It is used with aggregate functions and comes after where clause and before order by clause

The following sales table is used to explain the concept:

CustIDSellerIDTotal
1Null5
1Null10
1Null15
2Null20
3625
3630
3560
3565
4690
45100
45105

Group by:
SELECT CustID, SellerID, Sum(Total) Total
FROM Sales
GROUP BY CustID, SellerID
ORDER BY CustID,SellerID

CustIDSellerIDtot
1Null30
2Null20
35125
3655
45205
4690

Having Clause:
SELECT CustID, SellerID, Sum(Total) Total
FROM Sales
GROUP BY CustID, SellerID
Having Sum(Total)>60
ORDER BY CustID,SellerID

CustIDSellerIDTotal
35125
45205
4690