SQL Server “cannot perform an aggregate function on an expression containing an aggregate or a subquery”, but Sybase can

前端 未结 1 403
刺人心
刺人心 2020-12-14 06:23

This issue has been discussed before, but none of the answers address my specific problem because I am dealing with different where clauses in the inner and outer selects.

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 06:52

    One option is to put the subquery in a 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 
    

    Perhaps a better option would be to use SUM with 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 Demo with both

    0 讨论(0)
提交回复
热议问题