shelter_inventory (table)
gid | pav_type | yes
1 | 1 | 1
2 | 1 | 1
3 | 0 | 1
4 | 2 | 1
5 | 2 | 0
this is the current query (does not display count = 0)
SELECT pav_type, count(*) FROM shelter_inventory
WHERE yes = 1 GROUP BY pav_type ORDER BY pav_type
and I want the result to display like this
pav_type | count(*)
0 | 1
1 | 2
2 | 1
3 | 0
How could I query on this case? I use PostgreSQL.
If your
pav_typevalues are sequential, then you could usegenerate_seriesin place of an external table:This yields:
This:
essentially generates an inlined table with a single column called
pav_typeand four rows: 0, 1, 2, 3. And you need to have thes.yes = 1in the join condition (rather than the WHERE) because you want theyes = 0values to be in the pre-grouped result set; ifs.yes = 1is in the WHERE clause then theyes = 0rows won’t be counted regardless of what the join condition is.If your
pav_typesdo not nicely fit withgenerate_series(i.e. not sequential or step-sequential) and you only have a small number of them, you could join to a VALUES expression:You need to make sure you get all the parentheses in the right places of course.
If you do have the
pav_typesin a separate table then do a LEFT OUTER JOIN to that table instead of using thegenerate_series. If yourpav_typesare not sequential and you have too many to sensibly put in a VALUES expression, then build a table to hold the validpav_typevalues and LEFT OUTER JOIN to that.