2013-04-01 37 views
16

此問題已經在前面討論過,但沒有一個答案能夠解決我的具體問題,因爲我正在處理不同的where子句內部和外部選擇。這個查詢在Sybase下執行得很好,但是在SQL Server下執行時會出現這篇文章標題中的錯誤。查詢是複雜的,但查詢的大致輪廓是:SQL Server「無法對包含聚合或子查詢的表達式執行聚合函數」,但Sybase可以

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' 

下面介紹的情況,我想解決:

  • 所有組代碼表示,除了「總」和'賽別人的
  • 組代碼‘總’代表所有種族的畢業生總數
  • 然而,多種族丟失,所以在比賽畢業生數加起來可能不總研究生計數
  • 這個缺失的數據是什麼需要計算

是否有無論如何重寫這使用派生表或連接,以獲得相同的結果?

更新:我創建了sample data and 3 solutions to my specific problem(2受sgeddes影響)。我添加的涉及將相關子查詢移動到FROM子句中的派生表。謝謝你們的幫助!

+0

什麼是語義應該成爲?你有四個''(但只有兩個''''')。 –

+0

你能否拼出你的任務,提供樣本數據和預期結果。另外請添加'sql-server'標籤到你的文章。 –

+1

添加了語義,問題描述以及所需的數據和解決方案。 – PillowMetal

回答

27

一種選擇是將子查詢中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

+0

而且,神奇的是,問題通過...... GROUP BY來解決,因此它是一個聚合。 ;) –

相關問題