1

我接近解决这个问题,但需要轻推才能完成。我的数据集有 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,Feb 应该有 2 个认证决定和 1 个见证审核。

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

4

2 回答 2

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

或者您可以COUNT使用CASE

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

两个查询都给出了结果:

|               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 |
于 2013-03-15T16:51:04.000 回答
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 值。

于 2013-03-15T16:59:23.480 回答