SQLServer 2008r2。我有一张桌子,每天每小时过去10分钟就有一张唱片。工作每运行一小时,它也会输入48条记录,代表对未来48小时内可能发生的事情的预测。注 - 在它进入48小时预报之前,它将删除上次输入的预测。因此,尽管它每小时进行48小时的预测,但系统中只有一次预测。在表中的相关字段是这样的:从一天中的某个小时起按日期分组
currentScore obsDate
9 2017-06-22 08:10:00
9 2017-06-22 07:10:00
9 2017-06-22 06:10:00
10 2017-06-22 05:10:00
... ...
我如何可以查询该表,并按照日期分组从一天中的某个时间?我希望这一天在上午6点开始,并在当天上午6点结束。我只需要表中的五条记录,一天前两位,未来两位。所以如果它的6月20日我想要6月18日,19日,20日,21日和22日。这是按日历日获得正确结果的查询。
SELECT cast(obsDate AS DATE) AS theDate
,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);
返回这个结果:
theDAte low med high
2017-06-18 23 0 0
2017-06-19 22 0 0
2017-06-20 5 19 0
2017-06-21 0 24 0
2017-06-22 0 9 0
有一个新的要求得到同样的结果,而是由集团和随后数必须是从早上6点到早上6点。例如:
第一个记录应该是从2017-06-17 06:00到2017-06-18 06:00 am 第二个记录应该是从2017-06-18 06:00到2017-06-19 06 :00am .... etc
我该怎么做?在此先感谢
UPDATE,我已经做了两两件事:
1..introduce蒂姆斯想法
2..I还增加额外的字段“numOfScores”显示有多少个小时的数据 的每一行代表
select
cast(dateadd(hour, -6, 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(dateadd(hour, -6, obsDate) as date)
order by cast(dateadd(hour, -6, obsDate) as date);
现在我得到这样的结果:
2017-06-18 5 5 0 0
2017-06-19 24 23 1 0
2017-06-20 24 1 23 0
2017-06-21 24 8 16 0
2017-06-22 24 1 23 0
2017-06-23 9 0 9 0
这告诉我,2017-06-18只有5小时值得分。我希望这第一行24小时值得。从17日上午6点到18日上午6点。这让我觉得我没有得到的结果,我希望
的23只具有9-11个小时OK,因为这是最近期的预测
更新:
我不认为它很容易在一个查询完成(如果可能的话),所以我会只使用五个查询,并特别指出日期&次来获得我的结果。这里e.g是前两个条件:
这可能会在这里工作select
sum(case when currentScore < 9 then 1 else 0 end) as numOfLOWRecs,
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 = 9999
and obsDate >= '2017-06-18 06:00' and obsDate < '2017-06-19 06:00'
select
sum(case when currentScore < 9 then 1 else 0 end) as numOfLOWRecs,
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 = 9999
and obsDate >= '2017-06-19 06:00' and obsDate < '2017-06-20 06:00'
HI @tim因为我是按日期数据类型分组的,所以我不能这样做。查询抛出这个。数据类型日期的日期函数dateadd不支持datepart小时。基表有小时记录,因此我认为我需要按日期数据类型进行分组? – Mat41
“obsDate”列的类型是什么?它是文字吗? –
diseaseScores.obsDate是SMALLDATETIME场 – Mat41