按日分组和条件计数问题

时间:2017-06-20 01:16:08

标签: sql sql-server sql-server-2008-r2

使用SQLServer 2008r2 - 我有一个每小时插入一次记录的表。我的查询的相关列是currentScore(int)和obsDate(smallDateTime)。我想获得按天分组的五条记录。今天,今天前两天(从午夜开始)和未来两天。因此,如果我的6月20日,我想要6月18日,19日,20日,21日和22日。我成功地这样做:

select dateadd(DAY,0, datediff(day,0, obsDate)) as theDate,  
count(currentScore) as numOfScores 
from diseaseScores
where siteID=8315 and obsDate > dateAdd(day, -2, (SELECT CONVERT(DATETIME, 
CONVERT(DATE, CURRENT_TIMESTAMP)) + '00:00'))   
group by dateadd(DAY,0, datediff(day,0, obsDate))
order by dateadd(DAY,0, datediff(day,0, obsDate)) 

我的记录集如下:

      theDate           numOfScores
2017-06-18 00:00:00.000    23
2017-06-19 00:00:00.000    22
2017-06-20 00:00:00.000    24
2017-06-21 00:00:00.000    24
2017-06-22 00:00:00.000     9

我希望再添加三列,这些列将计算特定范围内当前分数的数量。像这样的东西

CASE 
WHEN currentScore < 8 THEN COUNT(where currentScore < 8) as Low
WHEN currentScore > 8 and < 17  THEN COUNT(where currentScore > 8 and < 17) as Med
WHEN currentScore > 17 THEN COUNT(where currentScore > 17 ) as High

我可以选择一个案例吗?实现这一目标的最佳方法是什么?

提前致谢

以下是我希望实现的结果:

 theDAte   numOfScores  low   med   high
 2017-06-18   23        23    0     0
 2017-06-19   22        22    0     0
 2017-06-20   24        5     19    0
 2017-06-21   24        0     24    0
 2017-06-22   9         0     9     0

1 个答案:

答案 0 :(得分:1)

首先,使用cast(. . as date)。更清楚!然后你可以使用条件聚合做你想做的事情:

select cast(obsDate as date) as theDate,  
       count(currentScore) as numOfScores ,
       sum(case when currentScore < 8 then 1 else 0 end) as currentscore_low,
       sum(case when currentScore >= 8 and currentScore < 17 then 1 else 0 end) as currentscore_medium,
       sum(case when currentScore >= 17 then 1 else 0 end) as currentscore_high
from diseaseScores
where siteID = 8315 and
      obsDate >= cast(getdate() - 2 as date)  
group by cast(obsDate as date)
order by cast(obsDate as date);

注意:您原来的where子句只有日期条件的一半。我没有添加另一半,但是如果将来不超过两天应该非常明显。