Using FILTER to create a pivot table
In the previous exercise, you wrote a query that provided information on the number of parking violations (by their numerical code) issued by each of four agencies. The results contained all of the desired information but were presented in a format that included a duplicate display of each violation_code
up to four times (for every issuing_agency
selected) in the results. A more compact representation of the same data can be achieved through the creation of a pivot table.
In this exercise, you will write a query using the FILTER
clause to produce results in a pivot table format. This improved presentation of the data can more easily be used in the report for parking violations issued by each of the four agencies of interest.
Cet exercice fait partie du cours
Cleaning Data in PostgreSQL Databases
Instructions
- Define the
Police
column as the number of records for eachviolation_code
with anissuing_agency
value ofP
. - Define the
Sanitation
column as the number of records for eachviolation_code
with anissuing_agency
value ofS
. - Define the
Parks
column as the number of records for eachviolation_code
with anissuing_agency
value ofK
. - Define the
Transportation
column as the number of records for eachviolation_code
with anissuing_agency
value ofV
.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
SELECT
violation_code,
-- Define the "Police" column
COUNT(issuing_agency) FILTER (WHERE issuing_agency = '___') AS "Police",
-- Define the "Sanitation" column
COUNT(___) FILTER (WHERE ___ = '___') AS "___",
-- Define the "Parks" column
___(___) ___ (WHERE ___ = '___') AS "___",
-- Define the "Transportation" column
___(___) ___ (___ ___ = '___') AS "___"
FROM
parking_violation
GROUP BY
violation_code
ORDER BY
violation_code