2011-08-30 55 views
9

我有一個transactions表,它包含一個類別(category_id),金額(amount)和一個標誌(managed),它們可以是真或假。PostgreSQL有條件求和

我想顯示所有類別的列表,其中包括託管和非託管交易總數,例如

Category | managed_transactions | unmanaged_transactions 
Cat 1 |  124000   |  54000 
Cat 2 |  4000    |  0 
Cat 3 |  854000   |  1000000 

有沒有辦法做這樣的事情

Select category_id, 
     sum(amount) if (managed is true) as managed_transactions, 
     sum(amount) if (managed is false) as unmanaged_transactions 
from transactions 

我顯然粘在if managed is true部分...

回答

21

享受!

SELECT 
    category_id, 
    SUM(CASE WHEN managed THEN amount ELSE  0 END) AS managed_transactions, 
    SUM(CASE WHEN managed THEN  0 ELSE amount END) AS unmanaged_transactions 
FROM 
    transactions 
GROUP BY 
    category_id 
ORDER BY 
    category_id 
+0

啊!謝謝,我已經嘗試過'管理金額(金額)結束時'的情況,但它是相反的:o) – Pierre