databasepostgresql

Postgres - How to check if date doesn't exist in result table and if so set data to zero


I have a query that tells me for each client how many devices per month I have assigned.

But I have no entries for the months where there are not devices assigned:

enter image description here

I need to have these rows added like this:

clientId | date         | assigned
11       | 2024-02-01   | 3
11       | 2024-03-01   | 0
11       | 2024-04-01   | 0
11       | 2024-05-01   | 0
11       | 2024-06-01   | 163

This is my query:

select "clientId", date_trunc('month', "tsAssignation"), count("deviceId") as assigned
from "devicesAssignations"
group by "clientId", date_trunc('month', "tsAssignation")

Is there a way to do this?


Solution

  • Here it is. First make a list of all user ids and all months then left join it to your table.

    select t.client_id, s::date "Date", coalesce(assigned, 0) assigned
    from 
     (
      (select distinct client_id from the_table) cross join 
      generate_series('2024-01-01', '2024-12-01', interval '1 month') as s
     ) as t 
    left join the_table 
         on assigned_date = t.s and t.client_id = the_table.client_id
    order by t.client_id, "Date";
    

    DB-fiddle demo