我一直在努力寻找一个优雅的解决方案,并且认为我最终破解了它但现在却收到了错误
在包含外部引用的聚合表达式中指定了多个列。如果聚合的表达式包含外部引用,则该外部引用必须是表达式中引用的唯一列。
这令我很沮丧!
本质上,查询是:
select
u.username + ' ' + u.surname,
CASE WHEN ugt.type = 'Contract'
THEN
(
select sum(dbo.GET_INVOICE_WEEKLY_AVERAGE_VALUE(pc.placementid, u.UserId))
from PlacementConsultants pc
where pc.UserId = u.UserId
and pc.CommissionPerc >= 80
)
END
from usergradetypes ugt
inner join usergrades ug on ug.gradeid = ugt.usergradetypeid
inner join users u on u.userid = ug.userid
GET_INVOICE_WEEKLY_AVERAGE_VALUE函数如下
ALTER function [dbo].[GET_INVOICE_WEEKLY_AVERAGE_VALUE]( @placementid INT, @userid INT )
RETURNS numeric(9,2)
AS
BEGIN
DECLARE @retVal numeric(9,2)
DECLARE @rollingweeks int
SET @rollingweeks = (select ISNULL(rollingweeks,26) FROM UserGradeTypes ugt
inner join UserGrades ug on ugt.UserGradeTypeID = ug.gradeid
WHERE ug.userid = @userid)
SELECT @retVal =
sum(dbo.GET_INVOICE_NET_VALUE(id.InvoiceId)) / @rollingweeks from PlacementInvoices pli
inner join invoicedetails id on id.invoiceid = pli.InvoiceId
where pli.PlacementID = @placementid
and pli.CreatedOn between DATEADD(ww,-@rollingweeks,getdate()) and GETDATE()
RETURN @retVal
查询在没有总和的情况下运行良好,但是当我试图对交易的价值求和时,它正在倒下(我需要为摘要页面做)
答案 0 :(得分:1)
评论太长了。我不知道为什么会失败:
select sum(dbo.GET_INVOICE_WEEKLY_AVERAGE_VALUE(pc.placementid, u.UserId))
但这有效:
select sum(dbo.GET_INVOICE_WEEKLY_AVERAGE_VALUE(pc.placementid, pc.UserId))
很奇怪,似乎对我来说就像一个错误。
但是,错误消息表明sum()
中的所有列都需要来自 外引用表或内部引用表,但不是两个。我不明白这个的原因。我最好的猜测是混合两种类型的引用会使优化器混淆。
顺便说一下,我之前没有看过这条错误信息。
编辑:
它很容易重现,不需要函数调用:
with t as (select 1 as col)
select t.*,
(select sum(t2.col + t.col) from t t2) as newcol
from t;
非常有趣。我认为这可能违反标准。等效查询确实在Oracle上运行。