聚合不在列表中的列

时间:2018-03-20 09:52:57

标签: sql-server tsql

例如,我有下表:

declare @table table(val int, dt datetime)
insert into @table values
(10, '2018-3-20 16:00'),
(12, '2018-3-20 14:00'),
(14, '2018-3-20 12:00'),
(16, '2018-3-20 10:00'),
(10, '2018-3-19 14:00'),
(12, '2018-3-19 12:00'),
(14, '2018-3-19 10:00'),
(10, '2018-3-18 12:00'),
(12, '2018-3-18 10:00')

我尝试使用group by中的列进行聚合,这没关系:

select day, MAX(val) as max_by_value from
(
select DATEPART(DAY, dt) as day, val from @table
) q
group by day

它返回:

day max_by_value
18  12
19  14
20  16

现在我需要一天中的最大值,所以每天需要10个结果。 我尝试使用over,但它说Column '@table.dt' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

select DATEPART(DAY, dt), MAX(val) as max_by_value
,ROW_NUMBER() over (partition by DATEPART(DAY, dt) order by dt desc) as max_by_date
from @table
group by DATEPART(DAY, dt)

我理解为什么会收到此错误,但不明白如何解决我的问题。您能帮忙找到填补[max_by_date]列的方法吗?

结果我希望得到以下结果:

day max_by_value max_by_time
18  12           10
19  14           10
20  16           10

1 个答案:

答案 0 :(得分:3)

从2012版开始,您可以使用First_value窗口功能:

SELECT  DISTINCT DATEPART(DAY, dt), 
        MAX(val) OVER (partition by DATEPART(DAY, dt)) as max_by_value,
        FIRST_VALUE(val) OVER (partition by DATEPART(DAY, dt) order by dt desc) as max_by_date
FROM @table

注意:我已使用OVER子句代替MAX函数而不是group by

使用2008版本,您可以使用子查询:

SELECT  DISTINCT DATEPART(DAY, dt), 
        MAX(val) OVER (partition by DATEPART(DAY, dt)) as max_by_value,
        (
            SELECT TOP 1 val
            FROM @table as t1
            WHERE DATEPART(DAY, t1.dt) = DATEPART(DAY, t0.dt)
            ORDER BY dt DESC
        ) as max_by_date
FROM @table as t0