查找24小时内SQL的最大值

问题描述 投票:0回答:2

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

密钥(PK、FK、int) DT(小日期时间) 价值(真实)

DT 是一天中每半小时的日期时间以及相关值

例如

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 有什么想法吗?

sql datetime group-by max
2个回答
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

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.