从MS SQL 2014开始,当分区是DateTime列时,我试图获得“In_Max”的最大值。
在我的示例中,我想要检索此行:
2017-12-17T02: 08: 46.4 | 19977300
SQL:
SELECT DateTime,
sum(In_Max) OVER (PARTITION BY CAST(DateTime as date)
ORDER BY DateTime ASC
ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING
) AS sum1
FROM yourtable
http://sqlfiddle.com/#!6/91f0d/5
我是否必须从DateTime中提取日期和时间,然后应用排名?
答案 0 :(得分:0)
如果您只需要一行,则可以使用TOP (1)
和ORDER BY
:
SELECT top (1) DateTime,
sum(cast(In_Max as int)) OVER (PARTITION BY CAST(DateTime as date) ORDER BY DateTime ASC ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING) AS sum1
FROM yourtable
ORDER BY sum1 DESC;
Here是SQL小提琴。
答案 1 :(得分:0)
从你对Gordon回答的评论中我得知你想要在一个月内获得每天in_max
的最大值。这仅仅是聚合:
select
cast(datetime as date) as day,
max(in_max) -- or sum if you want the sum and not the maximum
from yourtable
where year(datetime) = 2017 and month(datetime) = 12
group by cast(datetime as date);