在过去的X天内按天计算多个状态

时间:2015-12-02 15:31:16

标签: mysql sql select group-by

我正在尝试查询在过去的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

任何人都可以帮我实现这个目标吗?我错了什么?

1 个答案:

答案 0 :(得分:2)

您可以先使用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小提琴设置SQL Fiddle