I am trying to count on rows that dont come up in the join. I want a count of 0 for days with no orders.
Want this query to return 0 next to dates that don't have any and not return null.
SELECT days.date,
COALESCE(Count(service_orders.id)::int) AS count
FROM (
SELECT To_char( Date_trunc('day', (CURRENT_DATE + offs)), 'YYYY-MM-DD' ) AS date,
trim(both ' ' FROM to_char(date_trunc('day', (CURRENT_DATE + offs)), 'day')) AS day
FROM generate_series(0, 60, 1) AS offs ) days
RIGHT OUTER JOIN
(
SELECT service_order.id,
to_char( date_trunc('day', service_order.date), 'YYYY-MM-DD' ) service_order_day
FROM service_order
LEFT JOIN order_
ON service_order.order_id = order_.id) service_orders
ON days.date = service_orders.service_order_day
GROUP BY days.date
ORDER BY days.date ASC;
2023-06-22 6
2023-06-23 5
NULL 15312
I don't want null! And I want days that have a count of 0 as well.
So what I want is
2023-06-22 6
2023-06-23 5
2023-06-24 0
2023-06-25 0
...
As I understand your question, you want the count of service orders for each day over the next 60 days (including days without any order).
You seem to be overcomplicating things here:
generate_seriesdirectly on dates (no need for an intermediate step with a series of numbers)order_is superfluous in the queryDoesn't this do what you ask for?
We could also use a
left joinand outer aggregation: