gpt4 book ai didi

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery",但 Sybase 可以

转载 作者:行者123 更新时间:2023-12-01 21:59:45 31 4
gpt4 key购买 nike

这个问题之前已经讨论过,但没有一个答案能解决我的具体问题,因为我正在处理内部和外部选择中的不同 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”代表所有种族的毕业生总数
  • 但是,缺少多种族,因此种族毕业生人数可能不会等于毕业生总数
  • 需要计算缺失的数据

有没有办法使用派生表或联接重写它以获得相同的结果?

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

最佳答案

一种选择是将子查询放在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

关于SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery",但 Sybase 可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15751241/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com