根据日期期限在数据透视表中计数

时间:2018-10-03 09:17:21

标签: mysql database pivot

我正在尝试为每月的列预订状态创建数据透视表

这是我的表和查询

select bkg.status,
       bkg.StartDate 
from tbl_booking bkg 
where bkg.StartDate between '2018-09-17' and '2018-10-17'  
order by bkg.StartDate

我希望使用

这样的格式
Date Period     sep | Oct | Nov 

Status 1         10 | 20  |30
Status 2         40 | 50  |60

我尝试了以下查询

SELECT bkg.StartDate ,bkg.status ,
count(if(bkg.StartDate between '2018-09-17' and '2018-10-17',bkg.status,0)) as 'sep',
count(if(bkg.StartDate between '2018-10-17' and '2018-11-17',bkg.status,0)) as 'Oct'
from tbl_booking bkg 
group by bkg.status

但这给了我类似

的结果

enter image description here

如果我删除分组依据,它会给出e结果

,我也尝试过

  SELECT bkg.status,
        count(CASE WHEN bkg.StartDate between '2018-09-17' and '2018-10-17' THEN bkg.status ELSE 0 END) AS 'sep',
        count(CASE WHEN bkg.StartDate between '2018-10-17' and '2018-11-17' THEN bkg.status ELSE 0 END) AS 'Oct'
    FROM tbl_booking bkg
GROUP BY bkg.status

位结果似乎相同。 enter image description here

对于介于'2018-10-17'和'2018-11-17'之间的日期,没有记录,因此它应该返回0,但它使我所有月份的所有计数值相同。

请提出我可以在查询中进行哪些修改

2 个答案:

答案 0 :(得分:0)

在使用count时删除else部分,因此当您将else 0放到它时对其进行计数,如果使用sum则可以,但是对于count则可以跳过else,因此它将其他值视为null并给您准确计数

SELECT bkg.status,
        count(CASE WHEN bkg.StartDate between '2018-09-17' and '2018-10-17' THEN bkg.status END) AS 'sep',
        count(CASE WHEN bkg.StartDate between '2018-10-17' and '2018-11-17' THEN bkg.status END) AS 'Oct'
    FROM tbl_booking bkg 
GROUP BY bkg.status

答案 1 :(得分:0)

count(if(bkg.StartDate between '2018-09-17' and '2018-10-17',bkg.status,0))

在您的上述代码中,即使您的IF条件失败,您也将返回 0 。现在,COUNT(0仍将其计为一行,因此您获得相同的行数。

条件为假时,您需要返回NULL。应该是这样的:

count(if(bkg.StartDate between '2018-09-17' and '2018-10-17',bkg.status,NULL))

如果条件失败,这将不计算行数。

以下是经过修订的总体查询:

SELECT bkg.StartDate ,bkg.status ,
count(if(bkg.StartDate between '2018-09-17' and '2018-10-17',bkg.status,NULL)) as 'sep',
count(if(bkg.StartDate between '2018-10-17' and '2018-11-17',bkg.status,NULL)) as 'Oct'
from tbl_booking bkg 
group by bkg.status