按日期部分分组,查找每条记录的单个值的总计数

时间:2018-02-19 21:13:00

标签: sql sql-server

这是表结构;

ID  Score  Valid    CreatedDate
1   A      1        2018-02-19 23:33:10.297
2   C      0        2018-02-19 23:32:40.700
3   B      1        2018-02-19 23:32:30.247
4   A      1        2018-02-19 23:31:37.153
5   B      0        2018-02-19 23:25:08.667
...

我需要找到每个分数的总数并且每个月都有效

我的意思是最终结果应该像

Month    A     B     C     D   E   Valid(1) NotValid(0) 
January  123   343   1021  98  12  1287     480
February 516   421   321   441 421 987      672   
...

这是我试过的;

SELECT DATEPART(year, CreatedDate) as Ay,
(select count(*) from TableResults where Score='A') as 'A',
(select count(*) from TableResults where Score='B') as 'B',
...
  FROM TableResults 
  group by DATEPART(MONTH, CreatedDate)

但无法计算如何计算每个月的所有分数。

1 个答案:

答案 0 :(得分:4)

使用条件聚合。

SELECT DATEPART(year, CreatedDate) as YR
, DATEPART(month, CreatedDate) MO
, sum(Case when score = 'A' then 1 else 0 end) as A
, sum(Case when score = 'B' then 1 else 0 end) as B
, sum(Case when score = 'C' then 1 else 0 end) as C
, sum(Case when score = 'D' then 1 else 0 end) as D
, sum(Case when score = 'E' then 1 else 0 end) as E
, sum(case when valid = 1 then 1 else 0 end) as Valid
, sum(case when valid = 0 then 1 else 0 end) as NotValid
FROM TableResults 
GROUP BY DATEPART(MONTH, CreatedDate), DATEPART(year, CreatedDate)

我不是选择中查询的忠实粉丝;我发现从长远来看,它们往往会导致性能问题。由于我们在这里聚合,我只是将条件逻辑应用于所有列。