gpt4 book ai didi

mysql - 过去 5 天按天分组

转载 作者:可可西里 更新时间:2023-11-01 07:29:00 32 4
gpt4 key购买 nike

我正在尝试选择过去 5 天的整数字段的总和,我需要将它分组为每一天。

我在确定分组时遇到了一些问题。到目前为止,这是我的 sql 查询:

select 
sum(`amount_sale`) as total
from `sales`
where the_date >= unix_timestamp((CURDATE() - INTERVAL 5 DAY))

这可以很好地生成所有 5 天的总和,但我需要将其分解,以便它显示过去 5 天中每一天的总和,即:

day 1 - $200

day 2- $500

day 3 - $20

等等

最佳答案

SELECT  DATE(FROM_UNIXTIME(the_date)) AS dt, SUM(amount_sale) AS total
FROM sales
WHERE the_date >= UNIX_TIMESTAMP((CURDATE() - INTERVAL 5 DAY))
GROUP BY
dt

要为缺少的日期返回 0:

SELECT  dt, COALESCE(SUM(amount_sale), 0) AS total
FROM (
SELECT CURDATE() - INTERVAL 1 DAY AS dt
UNION ALL
SELECT CURDATE() - INTERVAL 2 DAY AS dt
UNION ALL
SELECT CURDATE() - INTERVAL 3 DAY AS dt
UNION ALL
SELECT CURDATE() - INTERVAL 4 DAY AS dt
UNION ALL
SELECT CURDATE() - INTERVAL 5 DAY AS dt
) d
LEFT JOIN
sales
ON the_date >= UNIX_TIMESTAMP(dt)
AND the_date < UNIX_TIMESTAMP(dt + INTERVAL 1 DAY)
GROUP BY
dt

这不是一个非常优雅的解决方案,但是,MySQL 缺少一种从头开始生成记录集的方法。

关于mysql - 过去 5 天按天分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6792686/

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