gpt4 book ai didi

MySQL 查询按日期范围分组

转载 作者:行者123 更新时间:2023-11-30 00:54:36 24 4
gpt4 key购买 nike

我在执行此查询时遇到问题:

SELECT
YEAR(passDate) as Year,
count(*) AS total_amount
FROM
`dsp_drop_pass_details`
WHERE passDate
BETWEEN '2009-01-01'
AND '2012-05-01'
AND batch='DROPOUT'
GROUP BY YEAR(passDate)
ORDER BY YEAR(passDate)

输出---

Month      total amount
2011 30
2012 20

但我的愿望是

Month    total amount 
2009 0
2010 0
2011 40
2012 20

我想要 0,其中计数为 0

最佳答案

最简单的方法是有一个“年”表,其中包含所有想要的年份。

create table Years(yearValue int);

insert into years values (2001), (2002)..., (2020);

然后在您的实际表上执行左连接。

SELECT y.yearValue, COALESCE(COUNT(d.id), 0) --assumning you have a field id in dsp_drop_pass_details
FROM years y
LEFT join dsp_drop_pass_details d on y.yearValue = YEAR(d.passDate)
WHERE y.yearValue between 2009 and 2012
GROUP BY y.yearValue
ORDER BY y.yearValue;

关于MySQL 查询按日期范围分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20689889/

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