我有3个表,预算,收入和支出。
预算表:
收入表:
费用表:
这是我的SQL语句:
SELECT
Budgets.BudgetID, Budgets.BudgetName, Budgets.Username_FK,
Budgets.BudgetAmount, Budgets.SavePercentage,
Expenses.ExpensesID, Expenses.ExpensesAmount, Expenses.ExpensesCategory,
Income.IncomeID, Income.IncomeAmount, Income.IncomeCategory
FROM
Budgets
LEFT JOIN
Income ON Budgets.BudgetID = Income.BudgetID_FK
LEFT JOIN
Expenses ON Budgets.BudgetID = Expenses.BudgetID_FK
WHERE
BudgetName = '2019
结果如下:
根据我的Income
表,只有1条记录与BudgetID = 3
绑定,但是在左联接中,它是重复的。
理想情况下,我希望它在重复项上返回“ null”。我该怎么做?
答案 0 :(得分:2)
每个expenses
的{{1}}中有几行,因此您的联接产生了那么多行。我倾向于怀疑budgetID
也会发生同样的情况。
如果您想每income
行,那么一个选项是预聚合和budgetID
(或left join
)。假设您要每个预算的总费用和收入,您可以这样做:
outer apply
现在您要按select b.*, e.expenseAmount, i.amountAmount
from budgets b
left join (
select budgetID_FK, sum(expenseAmount) expenseAmount
from expenses
group by budgetID_FK
) e on e.budgetID_FK = b.budgetID
left join (
select budgetID_FK, sum(incomeAmount) incomeAmount
from income
group by budgetID_FK
) i on i.budgetID_FK = b.budgetID
对从属表中的行进行分组,因此看不到这些表的其他列,例如budgetID
或incomeCategory
(具有多个值)根据{{1}})。
答案 1 :(得分:0)
对于budgetID 3,您的费用表中有相同用户的4个费用(不同的费用ID)为50.00。我想您想要的是相同类别和预算ID(在这种情况下为budgetID 3)的总费用
SELECT
Budgets.BudgetID, Budgets.BudgetName, Budgets.Username_FK,
Budgets.BudgetAmount, Budgets.SavePercentage,
Income.IncomeID, Income.IncomeAmount, Income.IncomeCategory,
ex.ExpensesCategory,
ex.Total_ExpensesAmount,
FROM Budgets
LEFT JOIN Income ON Budgets.BudgetID = Income.BudgetID_FK
LEFT JOIN (Select BudgetID_FK, ExpensesCategory, SUM(ExpensesAmount) as Total_ExpensesAmount
FROM Expenses
GROUP BY BudgetID_FK, ExpensesCategory) ex ON Budgets.BudgetID = ex.BudgetID_FK
WHERE BudgetName = '2019'