SQL每隔12小时选择一次MAX数据

时间:2016-04-13 15:42:50

标签: sql sql-server

我有一张名为temp的表。在这张表中,我有日期和价值。

Date               | Value
2016/04/01 07:00am |   1
2016/04/01 09:00am |   2
2016/04/01 11:00am |   3
...
2016/04/01 07:00pm |   5
2016/04/01 11:00pm |   2
...
2016/04/02 07:00am |   10
2016/04/02 09:00am |   13
2016/04/02 11:00am |   1
...
2016/04/02 07:00pm |   32
2016/04/02 09:00pm |   40

我想回复:

Date               | Value
04/01/2016 11:00am | 3
04/01/2016 07:00pm | 5
04/02/2016 09:00am | 13
04/02/2016 09:00pm | 40

想法是以12小时为间隔进行分组,然后找到所述组的最大值。

到目前为止,我有:

SELECT t.date, max(t.value) 
FROM temp t
WHERE t.Date between DATEADD(hour, 7, '04/01/2016') and DATEADD(minute, 1859, '04/02/2016')
GROUP BY DATEPART(Hour, t.date)%12, t.date
ORDER BY Date

但它返回所有数据,没有12小时组。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您不希望MAX,因为您不希望按日期分组,您希望日期时间的单个实例具有最大值。因此,您可以ROW_NUMBER根据日期和上午/下午时段使用PARTITION来获取该时段内值最大的行(ORDER BY t.value DESC):

SELECT date, value
FROM
(SELECT t.date, 
    t.value,
    ROW_NUMBER() 
        OVER(PARTITION BY CAST(t.date AS date), CASE WHEN DATEPART(hour, t.date) < 12 THEN 0 ELSE 1 END 
        ORDER BY t.value DESC) AS rownum
    FROM temp t
    WHERE t.Date between DATEADD(hour, 7, '04/01/2016') and DATEADD(minute, 1859, '04/02/2016')
) max_val
WHERE max_val.rownum = 1
ORDER BY Date