Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. This query executed just fine under Sybase, but gives the error in the title of this post when executed under SQL Server. The query is complicated, but the general outline of the query is:

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' 

The following describes the situation I am trying to resolve:

  • all group codes represent races except for 'total' and 'others'
  • group code 'total' represents the total graduates of all races
  • however, multi-race is missing, so the race graduate counts may not add up to the total graduate counts
  • this missing data is what needs to be calculated

Is there anyway to rewrite this using derived tables or joins to get the same results?

Update: I created sample data and 3 solutions to my specific problem (2 influenced by sgeddes). The one that I added involves moving the correlated subquery to a derived table in the FROM clause. Thanks for the help guys!

like image 666
PillowMetal Avatar asked Apr 01 '13 20:04

PillowMetal


1 Answers

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

like image 133
sgeddes Avatar answered Oct 14 '22 05:10

sgeddes