我正在使用SQL Server 2014,我有以下SQL查询,它运行正常并提供以下输出:
SELECT
[PropertyCode], [BkgLeadTime], COUNT([Bkg Lead Time]) AS 'BLT COUNT'
FROM
BOOKINGLEADTIME_CTE
GROUP BY
[PropertyCode], [Bkg Lead Time]
输出:
PropertyCode BkgLeadTime BLT COUNT
----------------------------------------------
ZIL 1 4
ZIL 2 2
ZIL 5 1
ZIL 7 12
我需要更改上面的查询,以便我只得到一行结果。基本上,我想计算上面显示的输出的加权平均值。
我的新查询如下:
SELECT
[PropertyCode],
SUM([Bkg Lead Time] * COUNT([Bkg Lead Time])) / SUM (COUNT([Bkg Lead Time])) AS 'Weighted AVG BLT'
FROM
BOOKINGLEADTIME_CTE
GROUP BY
[PropertyCode]
但是,当我运行查询时,SSMS会抛出以下错误:
无法对包含聚合或子查询的表达式执行聚合函数。
如何修改查询以避免此错误?我知道它与我使用的聚合语法有关但我无法找到重写此查询的正确方法。
预期输出为:
PropertyCode Weighted AVG BLT
ZIL 5.10
答案 0 :(得分:3)
可能会帮助你
WITH CTE_TEST
AS
( SELECT [PropertyCode], [BkgLeadTime], COUNT([Bkg Lead Time]) AS 'BLT_COUNT'
FROM BOOKINGLEADTIME_CTE
GROUP BY [PropertyCode], [Bkg Lead Time]
)
SELECT SUM([BkgLeadTime]*[BLT_COUNT]) / SUM([BLT_COUNT]) FROM CTE_TEST
答案 1 :(得分:1)
试试这个,
SELECT [PropertyCode]
,(SUM([Bkg Lead Time]) * COUNT([Bkg Lead Time])) / COUNT([Bkg Lead Time]) AS 'Weighted AVG BLT'
FROM BOOKINGLEADTIME_CTE
GROUP BY [PropertyCode]