MySQL查询生成每月的日期,项目和计数表

时间:2013-03-15 07:29:51

标签: mysql count

我已经接近搞清楚了,但需要轻推才能完成。我的数据集包含1月,2月和3月的记录。

enter code here

Select
  cartypes.TypeName,
  Count(cartypes.TypeName) As Count,
  COUNT(MONTH(maindata.CreatedDate) = 1) As Jan,
  COUNT(MONTH(maindata.CreatedDate) = 2) As Feb
From maindata
  Inner Join cartypes
    On maindata.TypeID = cartypes.CarType_ID
Group By cartypes.TypeName

我的输出如下:

TypeName                      Count      Jan    Feb 
Accreditation Audit            23        1       0
Certificate Decision            5        1       0
Certification Decision          2        1       0
Complaint About Client          1        1       0
Customer Complaint              3        1       0
Internal Audit                  5        1       0 
Internal Finding                7        1       0
Preventative Action             1        1       0
Witness Audit                   1        0       1

我已经尝试了几种不同的方法来尝试获取每个记录的各种TypeName的计数,以便每个月都能正确计算,但是我已经碰壁了。例如,Jan应该在认证审核中显示23个,而2月应该有2个认证决策和1个证人审核。

我希望我已经足够清楚了。

2 个答案:

答案 0 :(得分:2)

您当前的查询非常接近最终查询。您需要使用CASE表达式来获取每个TypeName每月的计数:

Select
  cartypes.TypeName,
  Count(cartypes.TypeName) As Count,
  sum(case when MONTH(maindata.CreatedDate) = 1 then 1 else 0 end) As Jan,
  sum(case when MONTH(maindata.CreatedDate) = 2 then 1 else 0 end) As Feb
From maindata
Inner Join cartypes
  On maindata.TypeID = cartypes.CarType_ID
Group By cartypes.TypeName

请参阅SQL Fiddle with Demo

或者您可以将COUNTCASE

一起使用
Select
  cartypes.TypeName,
  Count(cartypes.TypeName) As Count,
  count(case when MONTH(maindata.CreatedDate) = 1 then cartypes.TypeName end) As Jan,
  count(case when MONTH(maindata.CreatedDate) = 2 then cartypes.TypeName end) As Feb
From maindata
Inner Join cartypes
  On maindata.TypeID = cartypes.CarType_ID
Group By cartypes.TypeName

请参阅SQL Fiddle with Demo

两个查询都给出了结果:

|               TYPENAME | COUNT | JAN | FEB |
----------------------------------------------
|    Accreditation Audit |     4 |   3 |   1 |
|   Certificate Decision |     1 |   0 |   1 |
| Certification Decision |     3 |   1 |   2 |
| Complaint About Client |     3 |   3 |   0 |
|     Customer Complaint |     3 |   0 |   3 |
|         Internal Audit |     2 |   2 |   0 |
|       Internal Finding |     1 |   1 |   0 |
|    Preventative Action |     5 |   0 |   5 |
|          Witness Audit |     5 |   4 |   1 |

答案 1 :(得分:1)

通过更改:

COUNT(MONTH(maindata.CreatedDate) = X) as [Jan,Feb,etc]

to

SUM(IF(MONTH(maindata.CreatedDate) = X, 1,0)) as [Jan,Feb,etc]

Jan,Feb等的列现在具有正确的值,这些值在所有月份聚合时,等于TypeName的Count值。