Saturday, September 07, 2013

TSQL Interview Question: Group By

Group by clause is used to group the data in a table. It groups same kind of data in one group. Generally group by used for aggregation function where requirement is to get count average sum etc for one particular group. Below is the example of group by and how it works.
Create Table #Employee(Id int identity(1,1),Name Varchar(100),Designation Varchar(100),Salary int)

Insert into #Employee Values('Rahul','SSE',30000)
Insert into #Employee Values('Rohit','SE',20000)
Insert into #Employee Values('Ronit','SE',20000)
Insert into #Employee Values('Rupesh','TL',40000)
Insert into #Employee Values('Ahishek','AM',50000)
Insert into #Employee Values('Rakesh','SSE',30000)
Insert into #Employee Values ('Ashok','AM',50000)
Insert into #Employee Values ('Puneet','SE',20000)
Insert into #Employee Values ('Vineet','SSE',40000)

/* group by as order by */
/*Let say i want the  employee list where salary is decreasing to increasing */
select name,salary from #Employee group by salary,name

/* For Aggregate function : Query for getting count fr employee against designation */
Select count(*),Designation from #Employee group by Designation
drop Table #Employee.

2 AM
3 SE
1 TL

KeyWord: SQL Server Interview Questions, SQL Server interview Questions and Answers, TSQL Interview Question.

No comments:

Post a Comment