SQL Server"无法对包含聚合或子查询的表达式执行聚合函数",但Sybase可以

Pil*_*tal 26 sql sql-server aggregate correlated-subquery

之前已经讨论过这个问题,但是没有一个答案解决了我的具体问题,因为我正在处理内部和外部选择中的不同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'
Run Code Online (Sandbox Code Playgroud)

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

  • 除"总计"和"其他"外,所有组代码均代表比赛
  • 组代码'total'代表所有种族的毕业生总数
  • 然而,多种族缺失,因此种族毕业生数量可能不等于毕业总数
  • 这个缺失的数据是需要计算的

无论如何使用派生表或联接来重写它以获得相同的结果?

更新:为我的具体问题创建了样本数据和3个解决方案(2个受sgeddes影响).我添加的那个涉及将相关子查询移动到FROM子句中的派生表.谢谢你的帮助!

sge*_*des 38

一种选择是将子查询放在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 
Run Code Online (Sandbox Code Playgroud)

也许是一个更好的选择是使用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
Run Code Online (Sandbox Code Playgroud)

两个SQL小提琴演示

  • 而且,神奇的是,这个问题是通过......“GROUP BY”解决的,所以它是一个聚合。;) (2认同)