SQL连接具有相同外键的三个表,不合并表2和3的数据

时间:2019-03-14 21:10:23

标签: sql-server left-join outer-join

我要完成的工作是联接三个具有相同外键的表。但我想显示表2和表3的详细信息,而不将它们组合成一行。在下面,您可以看到正在返回的数据的屏幕截图。 InvoiceAmount多次打印相同的金额。 “名称”来自第一个表,也是其他两个表中的外键(CC1)。 “ InvoiceAmount”和“ Description”来自第二个表,“ NetAmount”来自第三个表。

如果“ InvoiceAmount”和“ Description”具有值,则“ NetAmount”将为空

如果“ NetAmount”具有值,则“ InvoiceAmount”和“ Description”将为空

enter image description here

如果可能的话,下面是我希望如何在选择中打印数据。我不知道是否必须创建视图,或者是否可以通过Select查询来创建视图,或者甚至根本不可能。

Name         InvoiceAmount       Description            NetAmount 
19-SHOP        -10041.98         BULKITEMTRANSFER        NULL  
19-SHOP         NULL               NULL                   84.840625
19-SHOP         NULL               NULL                   109.8613
19-SHOP         NULL               NULL                   110.1601
19-SHOP         NULL               NULL                   154.5323
19-SHOP         NULL               NULL                   187.5742

下面附带的是我现在拥有的SQL,它确实按照我的要求执行,但我只是想不通,或者在任何地方都找不到如何打印数据(如上所示)。任何帮助将不胜感激!

SELECT j.Name, a.InvoiceAmount, a.Description, p.NetAmount FROM Job AS j LEFT OUTER JOIN APInvoiceBatchDetail AS a ON a.CC1 = j.Name LEFT OUTER JOIN PPEReport AS p ON p.CC1 = j.Name

下面是第一个表“ Job”的屏幕截图

enter image description here

下面是第二个表“ APInvoiceBatchDetail”的屏幕截图

enter image description here

下面是第三张表“ PPERecord”的屏幕截图

enter image description here

1 个答案:

答案 0 :(得分:1)

SELECT j.Name,  a.InvoiceAmount, a.Description, null as NetAmount 
FROM Job AS j
JOIN APInvoiceBatchDetail AS a ON a.CC1 = j.Name 

union all

SELECT j.Name,  null as InvoiceAmount, null as Description, p.NetAmount 
FROM Job AS j
JOIN PPEReport AS p ON p.CC1 = j.Name

如果您需要订单,可以这样:

SELECT Name, InvoiceAmount, Description, NetAmount
FROM (
  SELECT j.Name,  a.InvoiceAmount, a.Description, null as NetAmount,
         1 as ord 
  FROM Job AS j
  JOIN APInvoiceBatchDetail AS a ON a.CC1 = j.Name 

  union all

  SELECT j.Name,  null as InvoiceAmount, null as Description, p.NetAmount,
         2 as ord 
  FROM Job AS j
  JOIN PPEReport AS p ON p.CC1 = j.Name
) X
ORDER BY X.ORD, X.Name