Number of records created per day

I decided to use generate_series:

SELECT d AS "Day", count(mt.id)  FROM generate_series(
  (SELECT min(delivery_day) from message_templates),
  (SELECT max(delivery_day) from message_templates)
) d
left join message_templates mt on mt.delivery_day = d 
group by d.d

Query is working fine. Maybe there is better way of doing this?


You could use this:

WITH tmp AS 
( 
    SELECT m.program_id, a.n AS d
    FROM generate_series(1, 
        (SELECT MAX(deliver_day) FROM message_templates) 
    )  AS a(n)
    CROSS JOIN 
    (
        SELECT DISTINCT program_id
        FROM messages
    ) m
)
SELECT t.program_id,
    t.d AS "day", 
    COUNT(m.program_id) AS "count" -- COUNT(m.id) 
FROM tmp t
LEFT JOIN message_templates mt
ON t.d = mt.deliver_day 
LEFT JOIN messages m
ON m.message_template_id = mt.id AND t.program_id = m.program_id
GROUP BY t.program_id, t.d 
ORDER BY t.program_id, t.d; 

Tested in db-fiddle

Tags:

Sql

Postgresql