为什么这个T-SQL查询会抛出一个“聚合函数”错误消息?

时间:2021-05-03 15:40:22

I am using SQL Server 2014 and I have the following SQL query which runs fine and gives the following output:

我使用的是SQL Server 2014,我有以下SQL查询,运行良好,输出如下:

SELECT 
    [PropertyCode], [BkgLeadTime], COUNT([Bkg Lead Time]) AS 'BLT COUNT' 
FROM 
    BOOKINGLEADTIME_CTE
GROUP BY 
    [PropertyCode], [Bkg Lead Time]

Output:

输出:

PropertyCode     BkgLeadTime        BLT COUNT
----------------------------------------------
   ZIL               1                4
   ZIL               2                2
   ZIL               5                1
   ZIL               7                12

I need to change the above query so that I get only one row as a result. Basically, I want to compute the weighted average of the output shown above.

我需要更改上面的查询,以便结果只能得到一行。基本上,我想计算上面显示的输出的加权平均值。

My new query stands as follows:

我的新查询如下:

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]

However, SSMS is throwing the following error when I run the query:

但是,当我运行查询时,SSMS会抛出以下错误:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

不能对包含聚合或子查询的表达式执行聚合函数。

How do I modify my query to avoid this error? I understand it has to do with the aggregation syntax I've used but I can't find out the correct way to re-write this query.

如何修改查询以避免此错误?我知道它与我使用的聚合语法有关,但是我无法找到正确的方法来重写这个查询。

Expected output is:

预期的输出是:

PropertyCode    Weighted AVG BLT
   ZIL             5.10

2 个解决方案

#1


3  

May be this will help you

这对你有帮助吗?

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

#2


1  

Try like this,

这样的尝试,

SELECT [PropertyCode]
    ,(SUM([Bkg Lead Time]) * COUNT([Bkg Lead  Time])) / COUNT([Bkg Lead Time]) AS 'Weighted AVG BLT'
FROM BOOKINGLEADTIME_CTE
GROUP BY [PropertyCode]

#1


3  

May be this will help you

这对你有帮助吗?

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

#2


1  

Try like this,

这样的尝试,

SELECT [PropertyCode]
    ,(SUM([Bkg Lead Time]) * COUNT([Bkg Lead  Time])) / COUNT([Bkg Lead Time]) AS 'Weighted AVG BLT'
FROM BOOKINGLEADTIME_CTE
GROUP BY [PropertyCode]