gpt4 book ai didi

sql - 如何填补 MySQL 中的日期空白?

转载 作者:可可西里 更新时间:2023-11-01 08:08:27 24 4
gpt4 key购买 nike

我如何填补 MySQL 中的日期空白?这是我的查询:

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

它返回正确的结果集 - 但我想用零填充开始日期和结束日期之间的空白。我该怎么做?

最佳答案

您需要创建一个辅助表并用从startend 的所有日期填充它,然后用它LEFT JOIN表:

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

基本上,您在这里需要的是一个虚拟行源。

MySQL 是唯一缺少生成它的方法的主要系统。

PostgreSQL 实现了一个特殊的函数 generate_series 来做到这一点,而 OracleSQL Server 可以使用递归( CONNECT BY 和相应的递归 CTE

关于sql - 如何填补 MySQL 中的日期空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1877874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com