Sunday, February 17, 2013

SQL SERVER GROUP BY clause

SQL SERVER GROUP BY clause

GROUP BY clause  is used to group repeated data like dept number, year,job title,customer id, etc.,

EMPNOENAMEJOBMGRHIREDATESALCOMMDEPTNO
7369SMITHCLERK790212/17/1980 12:00:00 AM800.00
20
7499ALLENSALESMAN76982/20/1981 12:00:00 AM1600.00300.0030
7521WARDSALESMAN76982/22/1981 12:00:00 AM1250.00500.0030
7566JONESMANAGER78394/2/1981 12:00:00 AM2975.00
20
7654MARTINSALESMAN76989/28/1981 12:00:00 AM1250.001400.0030
7698BLAKEMANAGER78395/1/1981 12:00:00 AM2850.00
30
7782CLARKMANAGER78396/9/1981 12:00:00 AM2450.00
10
7839KINGPRESIDENT
11/17/1981 12:00:00 AM5000.00
10
7844TURNERSALESMAN76989/8/1981 12:00:00 AM1500.000.0030
7900JAMESCLERK769812/3/1981 12:00:00 AM950.00
30
7902FORDANALYST756612/3/1981 12:00:00 AM3000.00
20
7934MILLERCLERK77821/23/1982 12:00:00 AM1300.00
10
 

Ex:  get total  number of employees from each department 


select deptno,count(*) total from emp group by deptno

deptno    total
10    3
20    3
30    6
 
Ex: get number of employees in each job title.
 
select job,count(*) total from emp group by job
 
job    total
ANALYST    1
CLERK    3
MANAGER    3
PRESIDENT    1
SALESMAN    4
 
Ex: get average salary by job category
select job,avg(sal) 'avg salary' from emp group by job

job    avg salary

ANALYST    3000.000000
CLERK    1016.666666
MANAGER    2758.333333
PRESIDENT    5000.000000
SALESMAN    1400.000000

Ex: get order count for each year and month.

used Northwind Orders Table.

select Datepart(year,orderdate) Year,
Datepart(month,orderdate) month,
count(*) total from orders
group by Datepart(year,orderdate),Datepart(month,orderdate)
order by Datepart(year,orderdate),Datepart(month,orderdate)

1996    7    22
1996    8    25
1996    9    23
1996    10    26
1996    11    25
1996    12    31
1997    1    33
1997    2    29
1997    3    30
1997    4    31
1997    5    32
1997    6    30
1997    7    33
1997    8    33
1997    9    37
1997    10    38
1997    11    34
1997    12    48
1998    1    55
1998    2    54
1998    3    73
1998    4    74
1998    5    14

Tags:SQL SERVER GROUP BY clause ,SQL SERVEr DATE FUNCTION Datepart,SQL Server Aggregate function count

No comments:

Post a Comment