简体   繁体   English

获取每天最高价值的记录

[英]Get record with max value for each day

I want to get the record with max power value for each day, See the table below 我想获取每天最大功率值的记录,请参见下表

CREATE TABLE [dbo].[HourData]
(
    [ID] [bigint] NOT NULL,
    [Powers] [decimal](18, 4) NOT NULL,
    [DataHour] [int] NOT NULL,
    [StartDate] [datetime] NOT NULL,

    CONSTRAINT [PK_HourData] 
        PRIMARY KEY CLUSTERED ([ID] ASC, [HourShow] ASC, [StartDate] ASC)
                    WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, 
                          ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) 

The below query will get max Powers usage for each day, but how can I get the record itself, Suppose if I need DataHour how can I get it, I can't include it in GroupBy clause. 下面的查询将获取每天的最大Powers使用量,但是如何获取记录本身呢?假设我需要DataHour,如何获取记录,不能将其包含在GroupBy子句中。

SELECT
    CAST(t.[StartDate] as DATE), 
    MAX(t.Powers) as 'Peak Power Each Day'
FROM 
    [HourData] t  
WHERE
    CONVERT(date, [StartDate]) BETWEEN CONVERT(date, '2016-12-01 09:45:59.240') 
                                   AND CONVERT(date,'2016-12-08 09:45:59.240')
 GROUP BY 
     CAST(t.[StartDate] AS DATE) 
 ORDER BY
     CAST(t.[StartDate] AS DATE)

You can get the entire record using window functions. 您可以使用窗口功能获取整个记录。 The following gets all the maxima on a each day: 以下是每天的所有最大值:

SELECT hd.*
FROM (SELECT hd.*,
             MAX(hd.Powers) OVER (PARTITION BY CAST(hd.StartDate as Date)) as maxpowers
      FROM HourData hd 
     ) hd
WHERE CONVERT(date, StartDate ) between '2016-12-01' and '2016-12-08' AND
      powers = maxpowers;

If you want one (arbitrarily): 如果您想要(任意):

SELECT hd.*
FROM (SELECT hd.*,
             ROW_NUMBER() OVER (PARTITION BY CAST(hd.StartDate as Date) ORDER BY hd.powers DESC) as seqnum
      FROM HourData hd 
     ) hd
WHERE CONVERT(date, StartDate ) between '2016-12-01' and '2016-12-08' AND
      seqnum = 1;

Note that I removed the time component from the between comparisons. 请注意,我从两次比较between删除了时间部分。 The conversion to date removes the time component anyway. 无论如何,转换为日期都会删除时间部分。 This is simpler. 这比较简单。

What is returned is in the SELECT part of the query. 返回的内容在查询的SELECT部分中。 SELECT * returns the entire entry. SELECT *返回整个条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM