2015-12-03 96 views
1

我有兩個子查詢,其中一個返回一組數據併合計分組中的一列,另一個執行相同的操作,但條件是批准日期不是't null。二是再加入和選擇得到這樣的結果:對於子查詢分組中的彙總列SQL返回零

ID - Requested - Approved

如果我現在運行它,它會返回像1 - 2 - NULL,因爲記錄我m測試與未批准。在這種情況下,我希望「Approved」列顯示0而不是「NULL」。我足夠新,複雜的查詢,我不知道如何做到這一點,但我確信這是可能的。

順便說一句,這是與MS SQL服務器,所以T-SQL之類的很好,如果它更容易。

這裏的查詢,因爲它現在是:

select sr.ItemID, Requested, Approved from 

(select sri.ItemID, Requested = sum(sri.Quantity) from SupplyRequestItem as sri inner join 
SupplyRequest as sr on sr.ID = sri.RequestID 
group by sri.ItemID) as sr left outer join 

(select sri.ItemID, Approved = sum(sri.Quantity) from SupplyRequestItem as sri inner join 
SupplyRequest as sr on sr.ID = sri.RequestID 
where sr.ApprovedDate is not null 
group by sri.ItemID) as asr on sr.ItemID = asr.ItemID 
+0

這是一個很好的開始。 http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/ –

回答

3

可以使用條件聚集,做一個簡單的方法。根據您的需要更改case表達式。

select sri.ItemID, 
Requested = sum(case when sr.ApprovedDate is null then sri.Quantity else 0 end), 
Approved = sum(case when sr.ApprovedDate is not null then sri.Quantity else 0 end) 
from SupplyRequestItem as sri 
inner join SupplyRequest as sr on sr.ID = sri.RequestID 
group by sri.ItemID 
+0

我已經擺弄這種情況下的陳述,但試圖把他們sum()調用之外。這比我之前做的更優雅,謝謝! – Yushatak