20 July 2016

Group by and Having Clause - SQL Server


Group by clause is used to remove duplicate rows and keep rows unique.  While using aggregate functions like Sum,Avg etc... group by clause will be useful.  
After get the result set by using group by clause, if you want some specific data from the result set, having clause will be useful.




Let us suppose we have a table #tmp_Studentmarks which is having student marks information in different subjects.

CREATE TABLE #tmp_Studentmarks
(
Namec VARCHAR(100),
Subj VARCHAR(100),
Marks INT
)

INSERT INTO #tmp_Studentmarks 
VALUES
('S1','Telugu',80),('S1','English',90),('S1','Maths',95),
('S2','Telugu',70),('S2','English',90),('S2','Maths',95),
('S3','Telugu',60),('S3','English',74),('S3','Maths',96),

('S4','Telugu',55),('S4','English',75),('S4','Maths',94)

If you want marks percentage of each student, we have to use the AVG function with  group by clause like below. 

SELECT Namec,Avg(Marks) FROM #tmp_Studentmarks GROUP BY Namec

Here Group by clause create a single record for each student and using Avg function, gets average of marks in all his  subjects.


Namec
Percent(%)
S1
88
S2
85
S3
76
S4
74

If you want information of the student  Who are having percentage grater than 80 then we have to write having clause like below 

SELECT Namec,Avg(Marks) [Percent(%)] FROM #tmp_Studentmarks GROUP BY Namec having Avg(Marks)>80

Namec
Percent(%)
S1
88
S2
85

That means, after group the data, if you want to filter again the final result set, we have to use having clause.

No comments:

Post a Comment