2011-05-23 61 views
1

這是一個通用的SQL問題,但是如果您必須知道數據庫是Firebird的話。SQL - 每列的條件

我有這個表(簡體):

 
user amount type 
-------------------- 
john 25  credit 
john 20  debit 
john 5  debit 
john 15  credit 
mike 15  credit 

我想有一個結果看起來像這樣,使用單個查詢:

 
user credit debit 
-------------------- 
john 40  25 
mike 15  NULL 
Where credit = SUM(amount) WHERE type=credit 
    and debit = SUM(amount) WHERE type=debit 

基本上我想有結果基於字段的SUM(在這種情況下爲金額)上的多個字段,但是在不同的條件下(在這種情況下是類型)。

在此先感謝您的任何建議。

回答

5

標準SQL將是:

SELECT "user", 
    SUM(CASE WHEN type='credit' then amount END) as Credit, 
    SUM(CASE WHEN type='debit' then amount END) as Debit 
FROM 
    "table" 
GROUP BY 
    "user" 
+0

+1。沒有什麼像聚合的舊CASE。 – 2011-05-23 16:22:50

+0

+1,儘管您需要引用'「user」(並且匹配列聲明的大小寫)。 USER是CURRENT_USER的Firebird同義詞,它不會像當前寫入的那樣在查詢中給出相當的結果。 :) – pilcrow 2011-05-24 04:07:30

+0

@pilcrow:你當然是對的,但這不就是一個模板嗎?如果你認爲這個查詢應該立即運行,你應該提到'table'也必須被引用。 :) – 2011-05-24 05:27:43

2

我不知道火鳥是怎麼做的,但你可以這樣做:

SELECT user, 
sum(SELECT amount FROM table AS t2 WHERE t2.user = t1.user AND type="credit") AS credit, 
sum(SELECT amount FROM table AS t3 WHERE t3.user = t1.user AND type="debit") AS debit 
FROM table AS t1 
GROUP BY user 
ORDER BY user 

我引用什麼,我認爲這將是在PostgreSQL中,如果能夠幫助你找到你所需要的。

0

試試這個:

SELECT credit.user_name, credit.cre, debit.deb 
    FROM (SELECT user_name, SUM(amount) cre FROM t WHERE TYPE = 'credit' GROUP BY user_name) credit 
    LEFT OUTER JOIN (SELECT user_name, SUM(amount) deb 
        FROM t 
        WHERE TYPE = 'debit' 
        GROUP BY user_name) debit 
    ON (credit.user_name = debit.user_name)