2014-01-22 80 views
1

根據條件自動加入表如果有人能夠幫助我處理我的查詢,我將不勝感激。 我有一個包含CurrenciesAmounts每個貨幣的表格。 我的第一個查詢是:根據條件t-sql

select Currency, SUM(Amount) amnt from [MyTable] 
where CODE in(410, 420) 
group by Currency 

所以,我得到:

Currency | amnt 
USD  | 15 

我想從我的表顯示所有可用的貨幣,並用這個結果來加入他們的行列(金額爲這些貨幣必須爲空)

Currency | amnt 
USD  | 15 
EUR  | 
AED  | 

我通過查詢獲取所有貨幣列表:

select currency from [MyTable] group by currency 

那麼,我怎樣才能加入這兩個查詢?

在此先感謝!

回答

1

試試這個:

SELECT a.Currency, SUM(CASE WHEN a.CODE IN (410, 420) THEN a.Amount ELSE 0 END) amnt 
FROM MyTable a 
GROUP BY a.Currency 

OR

SELECT A.Currency, SUM(B.Amount) amnt 
FROM (SELECT DISTINCT Currency FROM MyTable) A 
LEFT JOIN MyTable B ON A.Currency = B.Currency AND B.CODE IN (410, 420) 
GROUP BY A.Currency 

OR

SELECT A.Currency, SUM(B.Amount) amnt 
FROM (SELECT Currency FROM MyTable GROUP BY Currency) A 
LEFT JOIN MyTable B ON A.Currency = B.Currency AND B.CODE IN (410, 420) 
GROUP BY A.Currency 
+0

完美,謝謝! –

+0

@GyuzalRakhmayeva最受歡迎的... –