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)
以下描述了我要解决的情况:
无论如何使用派生表或联接来重写它以获得相同的结果?
更新:我为我的具体问题创建了样本数据和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)
也许是一个更好的选择是使用SUM有CASE:
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)
| 归档时间: |
|
| 查看次数: |
88190 次 |
| 最近记录: |