Tuesday, 17 September 2013

How to group by and include zero sums

How to group by and include zero sums

I'm trying to write a query that returns sums of transactions within every
category the user has created in my application. My current query works
fine but it does not display a category if no transactions have been made
under that category yet. I want my query to display every category even if
the sum of everything is 0.
I looked up how to do it and was suggested to use a LEFT/RIGHT OUTER JOIN
but it doesn't do what I want.
I am accessing a Microsoft Access 2007 Database via Windows C#
Application. This is my current query:
SELECT Categories.CategoryName ,
SUM( Transactions.TransactionCredit ) as CreditSum ,
SUM( Transactions.TransactionDebit ) as DebitSum ,
SUM( Transactions.TransactionCredit ) -
SUM( Transactions.TransactionDebit ) as Difference ,
SUM( Transactions.TransactionDebit ) /
( SELECT SUM(TransactionDebit)
FROM Transactions
WHERE AccountID = {currentAccountId}
) as 'Percent of Total Debit'
FROM Categories
LEFT JOIN Transactions on Categories.CategoryName = Transactions.CategoryName
WHERE Transactions.AccountID = {currentAccountId}
AND TransactionDate >= {startDate}
AND TransactionDate <= {endDate}
GROUP BY Categories.CategoryName

No comments:

Post a Comment