This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing one demonstration of PostgreSQL GROUPING SETS.
This is very useful for PostgreSQL Database Developers who require to perform multiple GROUP BY in one single query.
Now take one example, you want to find the count of Employee based on two columns: Employee Department , Employee Joining Year.
For this query, you have to write different two queries and If you want to combine results of both the query, you should use UNION clause.
But using GROUPING SETS, we can prepare this result into one single query.
Below is a full demonstration of this:
Create a table with Sample data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
CREATE TABLE tbl_Employees ( EmpID INT ,EmpName CHARACTER VARYING ,EmpDepartment CHARACTER VARYING ,JoiningDate TIMESTAMP WITHOUT TIME ZONE ); INSERT INTO tbl_Employees VALUES (1,'Anvesh','Database','2012-09-06') ,(2,'Roy','Animation','2012-10-08') ,(3,'Martin','JAVA','2013-12-25') ,(4,'Eric','JAVA','2014-01-26') ,(5,'Jenny','JAVA','2014-05-20') ,(6,'Kavita','Database','2014-12-12') ,(7,'Marlin','SQL','2015-08-08') ,(8,'Mahesh','PHP','2016-06-16'); |
Count of Employee, Group By Department column:
1 2 3 4 5 |
SELECT EmpDepartment ,COUNT(1) AS EmployeeCount FROM tbl_Employees GROUP BY EmpDepartment; |
Count of Employee, Group By Joining Year:
1 2 3 4 5 |
SELECT EXTRACT(YEAR FROM JoiningDate) AS JoiningYear ,COUNT(1) AS EmployeeCount FROM tbl_Employees GROUP BY EXTRACT(YEAR FROM JoiningDate); |
GROUP BY above two queries using GROUPING SETS:
1 2 3 4 5 6 |
SELECT EmpDepartment ,EXTRACT(YEAR FROM JoiningDate) AS JoiningYear ,COUNT(1) AS EmployeeCount FROM tbl_Employees GROUP BY GROUPING SETS (EmpDepartment,EXTRACT(YEAR FROM JoiningDate)); |
The Result:
1 2 3 4 5 6 7 8 9 10 11 12 |
EmpDepartment | JoiningYear | EmployeeCount --------------------------------------------- Animation 1 Database 2 JAVA 3 PHP 1 SQL 1 2012 2 2013 1 2014 3 2015 1 2016 1 |