2011-07-18 78 views
2

我有一個事務表和一個標記表。我想獲得按標記分組的交易表中所有交易的總和。有兩種不同類型的交易:「預算」和「實際」組合兩個由同一列分組的GROUP BY查詢

這個查詢將返回我什麼,我想爲「預算」的交易:

SELECT tg.name as tag, SUM(amount) as budgetTotal 
    FROM transaction tx 
    JOIN transaction_tag tt ON tt.transaction_id = tx.id 
    JOIN tag tg ON tg.id = tt.tag_id 
    WHERE tx.type = "budget" 
    AND tx.date >= '2011-07-15' 
    AND tx.date < '2011-08-15' 
GROUP BY tg.name 

,當然還有相當多的「同一個查詢實際的」交易:

SELECT tg.name as tag, SUM(amount) as actualTotal 
    FROM transaction tx 
    JOIN transaction_tag tt ON tt.transaction_id = tx.id 
    JOIN tag tg ON tg.id = tt.tag_id 
    WHERE tx.type = "actual" 
    AND tx.date >= '2011-07-15' 
    AND tx.date < '2011-08-15' 
GROUP BY tg.name 

我的問題:我怎麼組這兩個查詢的結果,成一個,所以我得到一個結果表有三列:標籤,budgetTotal和actualTotal?

回答

3

試試這個:

SELECT tg.name, 
     CASE WHEN tx.type = "actual" THEN SUM(amount) END AS actualTotal, 
     CASE WHEN tx.type = "budget" THEN SUM(amount) END AS budgetTotal 
    FROM.... 
    WHERE tx.type IN ("actual", "budget") 
    AND .... 
    GROUP BY tg.name 
+1

不它需要是'SUM(CASE WHITE tx.type =「actual」THEN amount END)AS actualTotal,'和分別代表'budgetTotal'?我的意思是,當你使用GROUP BY而不使用聚合(在這種情況下爲SUM)時,你不應該引用'tx.type'。 –

+0

在查詢中,如果您在列上使用總數或計數或任何函數,則必須在所有列上執行[group by],不管您是否使用 ,如select a,b,c,sum(a),sum(b )從x group by a,b,c – Shahzeb

+1

@Mitch:但是你的回答是正確的(@ rsbarro's也是這樣),而這會在2'Total'列中顯示錯誤的結果。它將隨機地顯示「SUM(金額)」(在所有行上,而不僅僅是「實際」或「預算」)或「NULL」。 –

1
SELECT tg.name as tag, SUM(amount) as budgetTotal, 'budget' as rectype 
FROM transaction tx 
JOIN transaction_tag tt ON tt.transaction_id = tx.id 
JOIN tag tg ON tg.id = tt.tag_id 
WHERE tx.type = "budget" 
AND tx.date >= '2011-07-15' 
AND tx.date < '2011-08-15' 
GROUP BY tg.name 

UNION ALL 

SELECT tg.name as tag, SUM(amount) as actualTotal, , 'actual' as rectype 
FROM transaction tx 
JOIN transaction_tag tt ON tt.transaction_id = tx.id 
JOIN tag tg ON tg.id = tt.tag_id 
WHERE tx.type = "actual" 
AND tx.date >= '2011-07-15' 
AND tx.date < '2011-08-15' 
GROUP BY tg.name 
0

不是瞧不起對方的回答(這可能是更好的),但這裏是如何得到它作爲兩個單獨的行是否適合。此外,這個答案是可擴展到任意數量的tx.type不改變查詢(如果去掉標準路線的where子句中t.type):

SELECT tg.name as tag, tx.type, SUM(amount) as total 
    FROM transaction tx 
    JOIN transaction_tag tt ON tt.transaction_id = tx.id 
    JOIN tag tg ON tg.id = tt.tag_id 
    WHERE tx.date >= '2011-07-15' 
    AND tx.date < '2011-08-15' 
    AND tx.type in ("budget", "actual") 
GROUP BY tg.name, tx.type; 
+0

一個好的解決方案,但難以迭代爲我的目的(對AJAX調用的JSON響應) – Ben