0

我有一个每日事件列表如下:

EventTypeID INT (multiple events, not unique)
EventDate (cast(EventDate) as Date)
HeadCount INT

我需要制作这个:

EventDate, AvgHeadCountET, AvgHeadCountTotal

每天我都有每个 EventType 的平均 HeadCount 和当天所有事件的平均 HeadCount。

我已经使用#TempTables 完成了几次,但我不禁认为有一种更有效的方法可以做到这一点。

4

2 回答 2

1

就像是:

SELECT EventDate,EventTypeID
     , AVG(HeadCount) AS AvgHeadCountET
     --, AVG(AVG(HeadCount)) OVER (PARTITION BY EventDate) AS AvgHeadCountTotal 
     , SUM(SUM(HeadCount)) OVER (PARTITION BY EventDate)/COUNT(*) OVER (PARTITION BY EventDate) AS AvgHeadCountTotal 
FROM YourTable
GROUP BY EventDate,EventTypeID

AVGHeadCountTotal值将在上述每个 EventDate 的记录中重复。

于 2013-10-30T20:46:27.500 回答
1

为此,您需要明确计算平均值——即求和除以计数:

SELECT EventDate,EventTypeID,
       AVG(HeadCount) AS AvgHeadCountET,
       (sum(sum(HeadCount)) over (partition by EventDate) /
        count(*) over (partition by EventDate)
       ) as AvgHeadCountTotal
FROM t
GROUP BY EventDate, EventTypeID;

混合窗口函数和聚合函数确实会产生时髦的语法(例如sum(sum()),但它们确实可以一起工作。

是一个说明它的 SQLFiddle。

于 2013-10-30T21:09:20.510 回答