mysql 中间有空白的日期_如何填补MySQL中的日期空白?

bd96500e110b49cbb3cd949968f18be7.png

How i can fill date gaps in MySQL? Here is my query:

SELECT DATE(posted_at) AS date,

COUNT(*) AS total,

SUM(attitude = 'positive') AS positive,

SUM(attitude = 'neutral') AS neutral,

SUM(attitude = 'negative') AS negative

FROM `messages`

WHERE (`messages`.brand_id = 1)

AND (`messages`.`spam` = 0

AND `messages`.`duplicate` = 0

AND `messages`.`ignore` = 0)

GROUP BY date ORDER BY date

It returns proper result set - but i want to fill gaps between dates start and end by zeros. How i can do this?

解决方案

You'll need to create a helper table and fill it with all dates from start to end, then just LEFT JOIN with that table:

SELECT d.dt AS date,

COUNT(*) AS total,

SUM(attitude = 'positive') AS positive,

SUM(attitude = 'neutral') AS neutral,

SUM(attitude = 'negative') AS negative

FROM dates d

LEFT JOIN

messages m

ON m.posted_at >= d.dt

AND m.posted_at < d.dt + INTERVAL 1 DAYS

AND spam = 0

AND duplicate = 0

AND ignore = 0

GROUP BY

d.dt

ORDER BY

d.dt

Basically, what you need here is a dummy rowsource.

MySQL is the only major system which lacks a way to generate it.

PostgreSQL implements a special function generate_series to do that, while Oracle and SQL Server can use recursion (CONNECT BY and recursive CTEs, accordingly).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值