PostgreSQL 9.4 has introduced one of the very good FILTER CLAUSE which is used to apply filters in aggregate functions.
Using FILTER, You can use different types of aggregate functions without applying any GROUP BY CLAUSE.
Now Imagine, that I have one Student table and I want total number of Students based different grades.
What happened without FILTER CLAUSE, We have to perform this calculation in the individual SELECT query.
But with the use of FILTER CLAUSE we can perform aggregation based on different FILTER values in a single SQL Query.
Below is a small demonstration of this:
Create one Student table with sample data:
1 2 3 4 5 6 7 8 9 10 11 12 | CREATE TABLE tbl_Students ( StudID INT PRIMARY KEY ,StudentName CHARACTER VARYING ,Marks INTEGER ); INSERT INTO tbl_Students VALUES (1,'Anvesh',88),(2,'Jenny',55),(3,'Tushar',85) ,(4,'Kavita',75),(5,'Manas',42),(6,'Martin',69) ,(7,'Roy',95),(8,'Benny',92),(9,'Neevan',82) ,(10,'Lee',43),(11,'Loother',65),(12,'Eric',58); |
Apply FILTER clause to count number of Students based on Marks:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | SELECT COUNT(1) AS TotalStudents ,COUNT(1) FILTER (WHERE Marks BETWEEN 40 AND 60) AS TotalGrade_C ,COUNT(1) FILTER (WHERE Marks BETWEEN 60 AND 80) AS TotalGrade_B ,COUNT(1) FILTER (WHERE Marks BETWEEN 80 AND 100) AS TotalGrade_A FROM tbl_Students; /* Result: -------------- --------------- --------------- --------------- TotalStudents | TotalGrade_C | TotalGrade_B | TotalGrade_A --------------|---------------|---------------|--------------- 12 | 4 | 3 | 5 -------------- --------------- --------------- --------------- */ |
0 comments:
Post a Comment