SQL Server“不能对包含聚合或子查询的表达式执行聚合函数”,但 Sybase 可以

Posted

技术标签:

【中文标题】SQL Server“不能对包含聚合或子查询的表达式执行聚合函数”,但 Sybase 可以【英文标题】:SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can 【发布时间】:2013-03-22 23:42:17 【问题描述】:

这个问题之前已经讨论过,但没有一个答案能解决我的具体问题,因为我正在处理内部和外部选择中的不同 where 子句。此查询在 Sybase 下执行得很好,但在 SQL Server 下执行时会出现本文标题中的错误。查询比较复杂,但是查询的大致大纲是:

select sum ( t.graduates -
    ( select sum ( t1.graduates )
      from table as t1
      where t1.id = t.id and t1.group_code not in ('total', 'others' ) ) )
from table as t
where t.group_code = 'total'

以下描述了我试图解决的情况:

除“total”和“others”外,所有组代码都代表种族 组码“total”代表所有种族的毕业生总数 但是,缺少多种族,因此种族毕业生人数可能不会与毕业生总数相加 需要计算这些缺失的数据

是否可以使用派生表或连接来重写它以获得相同的结果?

更新:我创建了sample data and 3 solutions to my specific problem(2 受 sgeddes 影响)。我添加的一个涉及将相关子查询移动到 FROM 子句中的派生表。谢谢大家的帮助!

【问题讨论】:

语义应该是什么?您有四个(,但只有两个) 能否请您详细说明您的任务,提供示例数据和预期结果。也请在您的帖子中添加sql-server 标签。 添加了语义、问题描述以及所要求的数据和解决方案。 【参考方案1】:

一种选择是将子查询放在LEFT JOIN

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

也许更好的选择是将SUMCASE 一起使用:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

【讨论】:

而且,神奇的是,这个问题被...GROUP BY 解决了,所以它是一个聚合。 ;) 如果我想完全避免另一个 JOIN 并且想要 SUM() 函数中的 SELECT 怎么办?我无法摆脱同样的错误消息。

以上是关于SQL Server“不能对包含聚合或子查询的表达式执行聚合函数”,但 Sybase 可以的主要内容,如果未能解决你的问题,请参考以下文章