我正在使用SQL Server 2014,并且我有以下查询给出了一个特定的错误消息:“无法对包含聚合或子查询的表达式执行聚合函数”。
USE MyDatabase
SELECT [MTH],
[RoomTypeCode],
SUM ([RN] * [AdultCount] / SUM ([RN])) AS 'Weighted Adult Ratio',
SUM ([RN] * [ChildCount] / SUM ([RN])) AS 'Weighted Child Ratio'
FROM PaxRatio
WHERE [PropertyCode] = 'XYZ'
AND [MTH] between '2015-07-01' and '2016-09-30'
查询的目的是为我提供视图表中的AdultCount和ChildCount列的加权平均值(称为PaxRatio)。
我尝试过使用CTE表而不是VIEW表,但我仍然遇到同样的错误!
答案 0 :(得分:2)
我认为你只需改变括号的位置:
SELECT [MTH],
[RoomTypeCode],
SUM ([RN] * [AdultCount]) / SUM ([RN]) AS 'Weighted Adult Ratio',
SUM ([RN] * [ChildCount]) / SUM ([RN]) AS 'Weighted Child Ratio'
FROM PaxRatio
WHERE [PropertyCode] = 'XYZ'
AND [MTH] between '2015-07-01' and '2016-09-30'
答案 1 :(得分:0)
您无法在另一个SUM
功能中执行SUM
。您可以在单独的查询中计算SUM
并使用CROSS JOIN
以便在主查询中使用计算值:
SELECT [MTH],
[RoomTypeCode],
SUM ([RN] * [AdultCount] / sum_rn) AS 'Weighted Adult Ratio',
SUM ([RN] * [ChildCount] / sum_rn) AS 'Weighted Child Ratio'
FROM PaxRatio
CROSS JOIN (
SELECT SUM([RN]) AS sum_rn
FROM PaxRatio
WHERE [PropertyCode] = 'XYZ' AND
[MTH] BETWEEN '2015-07-01' AND '2016-09-30') t
WHERE [PropertyCode] = 'XYZ' AND
[MTH] between '2015-07-01' and '2016-09-30'