2013-06-23 50 views
3

我有以下表如何建立一個查詢(總和,GROUP BY)

# amount type 
1  10  0 
1  10  0 
1  5  1 
1  5  1 
2  10  0 
2  10  0 
2  5  1 
2  5  1 

其中0表示現金和1表示在類型列信貸

的問題是找到每個ID的總現金用量和信用金額以及總金額。

我在尋找查詢得到以下結果

# cash credit total 
1 20 10 30 
2 20 10 30 

我想用一個查詢,如果有可能

感謝

回答

4
SELECT id, 
SUM(CASE WHEN type = 0 THEN amount ELSE 0 END) as "cash", 
SUM(CASE WHEN type = 1 THEN amount ELSE 0 END) as "credit", 
SUM(amount) as "total" 
FROM your_table 
GROUP BY id 
+0

我真的讚賞謝謝很多偉大的作品 –

+0

歡迎您! –

2
SELECT 
    num, 
    SUM(CASE WHEN type=0 THEN amount END) cash, 
    SUM(CASE WHEN type=1 THEN amount END) credit, 
    SUM(amount) total 
FROM 
    yourtable 
GROUP BY num 
0
select id, 
     sum(amount) as "total", 
     CASE WHEN type = 0 THEN amount ELSE 0 END as "cash", 
     CASE WHEN type = 1 THEN amount ELSE 0 END as "credit", 
    from table 
group by id