SQL Server左联接产生重复项

时间:2020-06-01 15:32:09

标签: sql sql-server database left-join sql-server-2019

我有3个表,预算,收入和支出。

预算表:

enter image description here

收入表:

enter image description here

费用表:

enter image description here

这是我的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

结果如下:

enter image description here

根据我的Income表,只有1条记录与BudgetID = 3绑定,但是在左联接中,它是重复的。

理想情况下,我希望它在重复项上返回“ null”。我该怎么做?

2 个答案:

答案 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 对从属表中的行进行分组,因此看不到这些表的其他列,例如budgetIDincomeCategory(具有多个值)根据{{​​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'