2017-06-20 49 views
0

使用SQLServer 2008r2 - 我有一张表,每小时插入一条记录。我查询的相关列是currentScore(int)和obsDate(smallDateTime)。我希望得到五天的记录。今天,今天的两天(从午夜开始)和未来两天。因此,如果其6月20日我想19年6月18日,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 

我想再增加三列,将计算一定范围内的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 

我可以用select case来做这个吗?达到此目的的最佳方法是什么?

在此先感谢

这里是我想达到的效果:

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 
+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子句只有一半的日期条件。我没有补充另一半,但未来两天内应该是非常明显的。

+0

太好了,谢谢。它非常完美。我有一种感觉,我正在使用CASE错误。现在看起来很明显,当我看着你的查询。使用cast作为日期可以消除时间,因此在更少的字符中实现我的目标也很棒。再次感谢戈登,您的时间非常感谢! – Mat41