I’ve a Postgres table like this:
datetime | tenant_id | orders_today |
---|---|---|
2023-06-25 10:00 | tenant2 | 2 |
2023-06-25 10:00 | tenant1 | 1 |
2023-06-25 11:00 | tenant1 | 5 |
2023-06-25 11:00 | tenant2 | 2 |
2023-06-25 12:00 | tenant1 | 5 |
Note that a orders_today for tenant2 hasn’t yet been generated for time 12:00.
I use a query like this to summaries orders today:
SELECT datetime, SUM(orders_today)
FROM orders
GROUP BY datetime
But this gives me this result:
datetime | sum |
---|---|
2023-06-25 10:00 | 3 |
2023-06-25 11:00 | 7 |
2023-06-25 12:00 | 5 |
How can I make it ignore the group for time 12 where a count for tenant 2 is missing? And, if possible, can I make it use the previous value for tenant 2 from time 11?
2
Answers
If I understand correctly, you want to exclude a group of datetimes if a tenant is missing, if so, you can use the
having
clause with the condition that the number of tenants for each datetime must equal the total number of tenants:Assuming:
(datetime, tenant_id)
is thePRIMARY KEY
. So:UNIQUE
and bth columnsNOT NULL
.Generate all combinations of interest from tenant & timestamp,
LEFT JOIN
to your table,LEFT JOIN
to a possible substitute, then proceed:fiddle
Similar:
If my assumptions don’t hold, you have to be more specific.