我有一个这样的问题
SELECT
d.create_at :: DATE AS dates,
count(r.id) AS usages
FROM reports r LEFT JOIN dispatches d ON r.dispatch_id = d.id
LEFT JOIN messages m ON d.message_id = m.id
WHERE r.status = 'SUCCESS' AND r.update_at :: DATE BETWEEN DATE '2020-05-01' AND '2020-05-10' AND m.client_id = 6
GROUP BY dates
ORDER BY dates;
会产生这样的结果
因为没有2020-05-03和2020-05-08的数据,所以他们不会显示在结果上
如何添加那些没有数据的日期,并将计数数据0作为值?
抱歉,我对postgres和db都是新手
我已经从各地遵循了几种解决方案似乎还没有得到我想要的结果
我试着用生成序列,但没有结果出来
SELECT
x.day AS dates,
count(r.id) AS usages
FROM (
SELECT generate_series(timestamp '2020-05-01'
, timestamp '2020-05-10'
, interval '1 day')::date
) x(day)
left join dispatches d on d.create_at = x.day
LEFT JOIN reports r ON d.id = r.dispatch_id
LEFT JOIN messages m ON d.message_id = m.id
WHERE r.status = 'SUCCESS' AND r.update_at :: DATE BETWEEN DATE '2020-05-01' AND '2020-05-10' AND m.client_id = 6
GROUP BY dates
ORDER BY dates;
抱歉,我遗漏了一些明显的东西。任何帮助都将不胜感激谢谢!
2条答案
按热度按时间niwlg2el1#
请使用下面的查询,
wmomyfyw2#
很接近,但where子句将外部连接变回内部连接。您需要将该条件移到联接条件中。