获取每天最大值的记录

时间:2016-12-17 04:35:58

标签: sql sql-server sql-server-2008

我想获得每天最大功率值的记录,请参阅下表

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]
) 

以下查询将获得每天的最大功率使用量,但我如何获得记录本身,假设我是否需要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)

2 个答案:

答案 0 :(得分:0)

您可以使用窗口函数获取整个记录。以下内容获取每天的所有最大值:

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;

如果你想要一个(任意):

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;

请注意,我从between比较中删除了时间组件。到目前为止,转换会删除时间组件。这更简单。

答案 1 :(得分:0)

返回的内容位于查询的SELECT部分。 SELECT *返回整个条目。