根据条件t-sql连接表自身

时间:2014-01-22 09:51:07

标签: mysql sql sql-server select group-by

如果有人可以帮我查询,我会很感激。 我有一张包含每种货币CurrenciesAmounts的表格。 我的第一个问题是:

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 个答案:

答案 0 :(得分: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

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

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