gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 18:22:02 25 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/46496517/

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