Sql 按天分组和有条件计数问题

Sql 按天分组和有条件计数问题,sql,sql-server,sql-server-2008-r2,Sql,Sql Server,Sql Server 2008 R2,使用SQLServer2008R2-我有一个每小时插入一次记录的表。我的查询的相关列是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 numOfS

使用SQLServer2008R2-我有一个每小时插入一次记录的表。我的查询的相关列是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
我的记录集看起来是这样的:

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
我希望再增加三列,这将计算一定范围内currentScore的数量。像这样的

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
首先,使用
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);
选择cast(obsDate作为日期)作为日期,
将(currentScore)计算为NumofScore,
总和(当currentScore<8时,则为1,否则为0结束)为currentScore\u low,
求和(当currentScore>=8且currentScore<17时,则为1,否则为0结束)作为currentScore\u媒介,
总和(当currentScore>=17时,则为1,否则为0结束)为currentScore\u high
从疾病分数
其中siteID=8315和
obsDate>=强制转换(getdate()-2作为日期)
按演员分组(截止日期为日期)
铸造订单(截止日期为日期);

注意:原始的
where
子句只有日期条件的一半。我没有添加另一半,但很明显,如何在未来不超过两天的时间内完成任务。

编辑您的问题,并显示您希望获得的结果。太好了,谢谢。太完美了。我有一种感觉,我用错了CASE。现在当我看着你的时候,这似乎很明显。使用cast-as-date删除时间,因此在更少的字符中实现了我的目标,非常好。再次感谢戈登,非常感谢你抽出时间!