SQL-在左外部联接查询中添加缺失数据

时间:2015-07-27 05:02:26

标签: sql sql-server sql-server-2012

我有以下数据
部件

componentid  title
1            houseRent
2            medical
3            Travelling Allowance

empPayrollMaster

MasterID EmployeeID SalaryMonthID
1          101     1
2          102     1
3          103     1

empPayrollDetail

DetailID MasterID ComponentID amount
1        1         1           100
2        1         2           500
3        2        1            300
4        2        3            250
5        3        1            150
6        3        2            350
7        3        3            450

必需的输出

EmployeeID MasterID ComponentID amount
     101      1        1           100
     101      1        2           500
     101      1        3           0
     102      2        1            300
     102      1        2           0
     102      2        3            250
     103      3        1            150
     103      3        2            350
     103      3        3            450

如果我在componentsempPayrollDetail之间留下外部联接,要获得所需的输出,我在EmployeeID和MasterID以及数量列中得到null。如何修改左连接以获取所需的输出

5 个答案:

答案 0 :(得分:6)

您需要在CROSS JOINComponents上执行empPayrollMaster,以便首先生成员工和组件的所有组合。然后,使用LEFT JOIN empPayrollDetail ISNULL(amount, 0)NULL amount进行SELECT epm.EmployeeID, epm.MasterID, c.ComponentID, amount = ISNULL(epd.amount, 0) FROM empPayrollMaster epm CROSS JOIN Components c LEFT JOIN empPayrollDetail epd ON epd.MasterID = epm.MasterID AND epd.ComponentID = c.ComponentID 以获得结果。

SQL Fiddle

{{1}}

答案 1 :(得分:0)

如果您想要主表中每个员工的组件金额,您应该使用insull(payrole_detail.amount,0)或@Turophile指出的金额列的SQL标准函数coalesce(payrole_detail.amount,0)

答案 2 :(得分:0)

试试这个

  select empPayrollMaster.EmployeeID,empPayrollMaster.MasterID,
  Components.componentid,isnull(empPayrollDetail.amount,0) 
  from empPayrollMaster 
  left join Components
  on  empPayrollMaster.EmployeeID is not null 
  left join empPayrollDetail 
  on empPayrollDetail.MasterID = empPayrollMaster.MasterID
  and empPayrollDetail.ComponentID = Components.componentid

答案 3 :(得分:0)

试试这种方式

select c.EmployeeID,d.MasterID,c.ComponentID,isnull(d.amount,0) as amount from (
select * from Components a
Cross join empPayrollMaster b) c 
left outer join empPayrollDetail d on d.componentid  =c.componentid  

答案 4 :(得分:0)

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;