I have a transaction table, and a tag table. I want to get a sum of all transactions in the transaction table grouped by tag. There are two different types of transaction: “budget” and “actual”
This query will return me what I want for “budget” transactions:
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
And of course pretty much the same query for “actual” transactions:
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
My question: how do I group the results of these two queries, into one, so I get one results table with three columns: tag, budgetTotal and actualTotal?
Try this: