在24小时内查找最大值SQL

时间:2017-11-10 10:01:18

标签: sql datetime group-by max dt

需要一些帮助:)

所以我有一个包含以下列的记录表:

键(PK,FK,int) DT(smalldatetime) 价值(真实)

DT是一天中每半小时的日期时间,具有相关值

E.g。

Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100

我需要找到每24小时的最大值和相关的DT。对于特定的键和日期范围

目前我有:

    SELECT CAST(LEFT([DT],11) as smalldatetime) as 'DATE'
          ,max([VALUE]) as 'MAX_HH'


FROM TABLE 1

  WHERE DT > '6-nov-2016' and [KEY] = '1000'
  GROUP BY CAST(LEFT([DT],11) as smalldatetime)
  ORDER BY 'DATE'

但是这会返回日期的最大值,例如

Key       DT                       VALUE
1000      2010-01-01 00:00:00      100

关于如何拉动完整DT的任何想法?

谢谢你们!

2 个答案:

答案 0 :(得分:1)

假设您正在使用支持窗口函数的数据库,我们可以使用ROW_NUMBER()(或RANK,如果您想支持/引入与第一位相关的值):

declare @t table ([Key] int not null , DT smalldatetime not null, Value int not null)
insert into @t([Key],DT,VALUE) values
(1000,'2010-01-01T08:00:00',80 ),
(1000,'2010-01-01T08:30:00',75 ),
(1000,'2010-01-01T09:00:00',100)

;With Numbered as (
    select *,
    ROW_NUMBER() OVER (PARTITION BY [Key],CAST(DT as date) ORDER BY Value desc) as rn
    from @t
)
select * from Numbered
where rn=1

答案 1 :(得分:0)

达米恩的答案非常好,如果你不能(或想要)使用窗口函数,试试这个:

SELECT      T1.*
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT

顺便说一下,最好不要使用保留关键字作为对象名称(即date