Monday 27 April 2015

How to use Group By Clause in sql server ?




GROUP BY Clause is used in a select statement to collect data across multiple records and group the results by one or more columns.or we can say that.Group By clause is used for grouping the records of the database tables.The  Group By clause creates a single row for each group and this process is called aggregation. Using for  group by clause we have to use at least one aggregate function in Select statement. aggregate_function can be a function such as SUM, COUNT, MIN, MAX, or AVG functions.


Syntax of Group By
                                  Select Column1,Column2,Column3 from Table_Name
                                  Where Condition
                                  Group By Column1,.........   OR

                                  Select Column1,Column2,Column3 from Table_Name
                                  Where Condition
                                  Group By Column1,.........
                                  Order By Column2...... OR

                                  Select Column1,Column2,SUM(Column3)as Total from Table_Name
                                  Where Condition
                                  Group By Column1,......... 


 -- Create table in database first:-
CREATE TABLE [dbo].[Employee_Test](
      [Emp_ID] [int] NOT NULL,
      [Emp_name] [varchar](100)NOT NULL,
      [Emp_Sal] [int] NULL,
      [Age] [int] NULL,
      [Gender] [nchar](10)NOT NULL
) ON [PRIMARY]

--Now insert records into database table 
INSERT  INTO  [dbo].[Employee_Test] ([Emp_ID], [Emp_name], [Emp_Sal], [Age], [Gender])
 VALUES (1, N'Anees', 1000, 30, N'Male      ')
INSERT  INTO  [dbo].[Employee_Test] ([Emp_ID], [Emp_name], [Emp_Sal], [Age], [Gender])
 VALUES (2, N'Rinku', 1200, 45, N'Male      ')
INSERT  INTO  [dbo].[Employee_Test] ([Emp_ID], [Emp_name], [Emp_Sal], [Age], [Gender])
 VALUES (3, N'John', 1100, 25, N'Male      ')
INSERT  INTO  [dbo].[Employee_Test] ([Emp_ID], [Emp_name], [Emp_Sal], [Age], [Gender])
 VALUES (4, N'Stephen', 1300, 30, N'Male      ')
INSERT  INTO  [dbo].[Employee_Test] ([Emp_ID], [Emp_name], [Emp_Sal], [Age], [Gender])
 VALUES (5, N'Maria', 1400, 45, N'Female    ')
INSERT  INTO  [dbo].[Employee_Test] ([Emp_ID], [Emp_name], [Emp_Sal], [Age], [Gender])
 VALUES (6, N'Ankit', 1000, 25, N'Male      ')
INSERT  INTO  [dbo].[Employee_Test] ([Emp_ID], [Emp_name], [Emp_Sal], [Age], [Gender])

 VALUES (7, N'Renu', 1200, 30, N'Female    ')


--Select Query to select all records without Group by clause




Select Query Group by Gender
















Select Query Group by Age















Select Query Group by Age and using having clause also


No comments:

Post a Comment