【发布时间】:2022-01-07 15:37:16
【问题描述】:
一段时间以来,我一直在努力寻找一个优雅的解决方案,并认为我终于破解了它,但现在遇到了错误
在包含外部引用的聚合表达式中指定了多个列。如果要聚合的表达式包含外部引用,则该外部引用必须是表达式中引用的唯一列。
这让我很沮丧!
本质上,查询是:
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
查询在没有总和的情况下运行良好,但是当我尝试对交易的价值求和时,它会失败(我需要为摘要页面做这件事)
【问题讨论】:
-
如果在函数调用中将
u.UserId替换为pc.UserId会发生什么? -
@Mihai 很公平,但我不明白为什么当我运行一个函数时,我不能简单地对其进行求和?
-
@GordonLinoff 它接受命令!谢谢 - 为什么要这样做?
标签: sql sql-server-2008