I have two tables that look like this:
Categories ( CategoryId, Type, Name )
Transactions ( TxnId, DateTime, Amount, CategoryId )
I want to get the SUM
of all of the transactions for each category for each month.
I can do this by having a sproc (see below) that generates the sums for each category given a date-range (e.g. a month 2013-07-01 <= Transactions.DateTime < 2013-08-01
. However I don't know how to do that for all months in the database, so I decided I could run the sproc repeatedly (given different min/max dates) to get the sums for different months.
I would like to combine the results into a single table.
My category sum sproc looks like this:
SELECT
Categories.Name,
Categories.Type,
Categories.CategoryId,
CategorySpendingForMonth.Amount
FROM
Categories
LEFT OUTER JOIN (
SELECT
CategoryId,
SUM(Amount) AS Amount
FROM
Txns
WHERE
[DateTime] >= @fromDate
AND
[DateTime] < @toDate
GROUP BY
CategoryId
) AS CategorySpendingForMonth ON Categories.CategoryId = CategorySpendingForMonth.CategoryId
ORDER BY
Categories.Type,
Categories.Name
My result looks like this:
Name Type CatId Amount
Car 0 9 -183.22
Electricity 0 12 -86.05
Insurance 0 17 NULL
Internet 0 14 -39.99
Phone 0 23 -50.04
Rent 0 19 -2284.80
Xoom 0 25 -604.99
But I want it to look like this:
Name Type CatId June July Aug
Car 0 9 -183.22 -183.22 -183.22
Electricity 0 12 -86.05 -86.05 -86.05
Insurance 0 17 NULL -12.30 NULL
Internet 0 14 -39.99 -39.99 -39.99
Phone 0 23 -50.04 -50.04 -50.04
Rent 0 19 -2284.80 -2284.80 -2284.80
Xoom 0 25 -604.99 -604.99 -604.99
(and add additional columns for additional months)
So I was thinking I could simply call my sproc for each month I want to add the data for, but I don't know how to JOIN my existing data together like that (if it were vertical I'd use a UNION, but this is horizontal).
This is what I have in mind (invalid SQL):
SELECT
Name,
Type,
CategoryId,
Amount
FROM
EXEC CategoriesSummary( '2013-07-01', '2013-08-01' )
FOR i = 0 TO 12
LEFT OUTER JOIN CategoriesSummary( '2013-' + (7 + i) +'-01', '2013-' + (8 + 1) + '-01' )
NEXT
....but that's invalid, so what's the best way to solve this problem?
Thanks!