【问题标题】:Multiple columns in aggregated expression聚合表达式中的多个列
【发布时间】: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


【解决方案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 上运行。

【讨论】:

    猜你喜欢
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多