gpt4 book ai didi

mysql - 在最近 X 天内按天计算多个状态

转载 作者:行者123 更新时间:2023-11-29 02:19:32 26 4
gpt4 key购买 nike

我正在尝试查询以在过去 X 天内按天计算多个状态。我可以进行查询来计算这些,但输出不是我想要的,也许我的 GROUP BY 语句中有错误。这就是我现在所拥有的:

示例表:

date - status
02-12-2015 - 1
02-12-2015 - 1
02-12-2015 - 3
02-12-2015 - 2
03-12-2015 - 1
03-12-2015 - 2

我的查询:

SELECT
DATE_FORMAT( STR_TO_DATE( crdate , "%d-%m-%Y %H:%i:%S" ) , "%d-%m-%y" ) as date , COUNT(*) as countone
FROM TBL_NAME
WHERE status='1'
UNION
SELECT
DATE_FORMAT( STR_TO_DATE( crdate , "%d-%m-%Y %H:%i:%S" ) , "%d-%m-%y" ) as date , COUNT(*) as counttwo
FROM TBL_NAME
WHERE status='2'
UNION
SELECT
DATE_FORMAT( STR_TO_DATE( crdate , "%d-%m-%Y %H:%i:%S" ) , "%d-%m-%y" ) as date , COUNT(*) as countthree
FROM TBL_NAME
WHERE status='3'
GROUP BY DATE_FORMAT( STR_TO_DATE( crdate , "%d-%m-%Y %H:%i:%S" ) , "%d-%m-%y" ), status ORDER BY DATE_FORMAT( STR_TO_DATE( crdate , "%d-%m-%Y %H:%i:%S" ) , "%d-%m-%y" ) ASC

应该是下面的输出:

date - countone - counttwo - countthree
02-12-2015 - 2 - 1 - 1
03-12-2015 - 1 - 1 - 0

问题是我的输出只是按日期分组。我的输出如下:

date - countone
02-12-2015 - 2
02-12-2015 - 1
02-12-2015 - 1
03-12-2015 - 1
03-12-2015 - 1

谁能帮我实现这个目标?我哪里错了?

最佳答案

您可以先使用 group by 计算状态计数,然后旋转表以获得所需的结果。联合函数将始终连接行。

select datefield,
max(if(status=1,count,0)) as countone,
max(if(status=2,count,0)) as counttwo,
max(if(status=3,count,0)) as countthree
from (select datefield, status, count(*) as count
from TBL_NAME
group by datefield,status) A
group by datefield;

检查它的 SQL fiddle 设置 SQL Fiddle

关于mysql - 在最近 X 天内按天计算多个状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34046584/

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