我真的希望有人可以帮我解决这个棘手的问题。
我有一个不断接收数据的表(如数据日志) 该表正在接收数据24 * 7。 可以有很多记录。小时和许多名称A,B,C,D等。
表格RAW
LogTime Name Value
2015-05-16 00:29:00 A 03
2015-05-16 00:48:00 A 15
2015-05-16 00:29:00 B 30
2015-05-16 00:35:00 B 32
2015-05-16 00:59:00 B 66
2015-05-16 01:25:11 A 88
2015-05-16 01:52:00 A 100
2015-05-16 01:26:45 B 5
2015-05-16 01:57:00 B 51
午夜后的每一天,我都希望运行一个可以追溯到前一天的程序 XXXX-XX-XX 00:00:00到XXXX-XX-XX 23:59:59。 取每个名称的MAX值,按小时分组,并将结果插入另一个表格,格式如下
表格结果
TimeByHouer Name Value
2015-05-08 01:00:00 A 15
2015-05-08 01:00:00 B 66
2015-05-08 02:00:00 A 100
2015-05-08 02:00:00 B 51
答案 0 :(得分:0)
尝试此查询:
declare @t table(logtime datetime, name char(1), value int)
insert into @t(logtime, name, value) values
('2015-05-16 00:29:00', 'A', 3),
('2015-05-16 00:48:00', 'A', 15),
('2015-05-16 00:29:00', 'B', 30),
('2015-05-16 00:35:00', 'B', 32),
('2015-05-16 00:59:00', 'B', 66),
('2015-05-16 01:25:11', 'A', 88),
('2015-05-16 01:52:00', 'A', 100),
('2015-05-16 01:26:45', 'B', 5),
('2015-05-16 01:57:00', 'B', 51)
; with Hs(TimeByHouer, name, value) as (
Select H = DATETIMEFROMPARTS(DATEPART(YEAR, logtime), DATEPART(MONTH, logtime), DATEPART(DAY, logtime), DATEPART(HOUR, logtime), 0, 0, 0)
, name, value From @t
)
Select TimeByHouer, name, Max(value) From Hs Group By TimeByHouer, name
Order By TimeByHouer, name
2012年你也可以使用:
Select DATEADD(HOUR, DATEPART(HOUR, logtime), cast(cast(logtime as date) as datetime))