我正在使用contregation函数的组来汇总表(通过多个外键分组,值列,一个时间戳和时间戳列,该列已舍入到整个天数(。
但是有一列我需要在分组中获得第一行,而不是汇总值。我查看了first_value((,但它是窗口函数,而不是聚合函数。
在伪代码中,我想执行此[不存在]:
SELECT
ForeignKey1
,ForeignKey2
,MIN(StartTime) AS StartTime
,Foo
,AVG(Bar) AS Bar
,FIRST(Baz) AS Baz
FROM
Qux
GROUP BY
ForeignKey1
,ForeignKey2
,Foo
,CONVERT(DATE, StartTime)
如何获得第一个值而不是汇总值?
您可以在CTE中应用行号,然后拔出整个第一行,无需单独的MIN
汇总:
;With Ordered as (
SELECT
*,
ROW_NUMBER() OVER(
PARTITION BY
ForeignKey1
,ForeignKey2
,Foo
,CONVERT(DATE, StartTime)
ORDER BY StartTime) as rn,
AVG(Bar) OVER (
PARTITION BY
ForeignKey1
,ForeignKey2
,Foo
,CONVERT(DATE, StartTime)) as BarAvg
FROM Qux
)
SELECT * from Ordered
WHERE rn = 1