我正在尝试编写一个查询,该查询返回用户在我的应用程序中创建的每个类别中的事务总和。我当前的查询工作正常,但如果尚未在该类别下进行任何交易,它不会显示该类别。即使所有内容的总和为 0,我也希望我的查询显示每个类别。
我查找了如何做到这一点,并被建议使用 LEFT/RIGHT OUTER JOIN,但它并没有达到我想要的效果。
我正在通过 Windows C# 应用程序访问 Microsoft Access 2007 数据库。这是我当前的查询:
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
这就是它在我的 c# 应用程序中的编码方式:
queries.returnQuery("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 +
(enableDateFilter ? " AND Transactions.TransactionDate >= #" + startDate + "# AND Transactions.TransactionDate <= #" + endDate + "# " : " ") +
" GROUP BY Categories.CategoryName");