Tuesday, February 26, 2013

SQL Server Group By Clause

SQL Server Group By
                 --> groups repeated data in a column(s)/Aggregates data


Note: grouping on non-repeated columns such as Primary key/unique key will result entire rows in the table.

Syntax:
           select col1,col2,col3  from table
           group by col1,col2,col3.

syntax 2:
            select col1, max(col2) from table
            group by col1.
       

Here is the Emp table

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

Note:In this table deptno and job columns have repeated values. Which are meaningful in-context.

Grouping Data on Single Column(DeptNo)

--Get Employee Count for each department

select deptno, count(*) Employees from emp
group by Deptno

deptno    Employees
10    3
20    3
30    6


--Get Employee max salary for each department

select deptno, Max(sal) "Max Salary" from emp
group by Deptno

deptno    Max Salary
10    5000.00
20    3000.00
30    2850.00

Grouping Data on Multi-Column(DeptNo,JOB)

--Get Employee count from each department based on job titleselect deptno, job,count(*) Employees from emp
group by Deptno,job
 
deptno    job    Employees
20    ANALYST    1
10    CLERK    1
20    CLERK    1
30    CLERK    1
10    MANAGER    1
20    MANAGER    1
30    MANAGER    1
10    PRESIDENT    1
30    SALESMAN    4

--Get Employee Max Salary in each department and job.
select deptno, job,Max(sal) "Max Salary" from emp
group by Deptno,job
 
deptno    job    Employees
20    ANALYST    3000.00
10    CLERK    1300.00
20    CLERK    800.00
30    CLERK    950.00
10    MANAGER    2450.00
20    MANAGER    2975.00
30    MANAGER    2850.00
10    PRESIDENT    5000.00
30    SALESMAN    1600.00
 

 Note: All columns specified in the select list(except those in aggregate functions)  should be part of group by clause.

otherwise Msg 8120, Level 16, State 1, Line 18
Column 'emp.[]' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.



Tags: SQL Server Group By Clause, Group by Examples, Group by on single column, Group By on Multiple Column

No comments:

Post a Comment