之前已经讨论过这个问题,但是没有一个答案可以解决我的特定问题,因为我正在处理内部和外部selects中的不同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'
下面介绍了我要解决的情况:
无论如何,有没有使用派生表或联接重写它以获得相同的结果?
更新: 我为我的特定问题创建了示例数据和3个解决方案(其中2个受sgeddes影响)。我添加的内容涉及将相关子查询移动到FROM子句中的派生表。感谢您的帮助!
一种选择是将子查询放在LEFT JOIN:
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
也许是一个更好的选择是使用SUM有CASE:
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
两者的SQL Fiddle演示