SQL Server Join Query返回冗余行

时间:2018-04-17 08:53:20

标签: sql sql-server join left-join

我有两张桌子

tblMaster          tblTrans
ID  Desc           ID  IDMaster  Qty     Garage
==  ======         ==  ========= =====   =====
1   Type1          1   1         1       1
2   Type2          2   2         2       1
                   3   1         3       2
                   4   2         2       2
                   5   1         2       3
                   6   2         4       3

当我加入时我想要这个输出:

ID Desc  Garage1Qty  Garagae2Qty Garage3Qty  Garage4Qty
== ====  =========== =========== =========== ==========
1  Type1 1           3           2           null
2  Type2 2           2           4           null

请注意,“Garage”值可以在将来添加。那么我该如何实现呢?试过这个:

SELECT M.*, Garage1Qty.*, Garage2Qty.* FROM tblMaster M
LEFT JOIN (  SELECT a.Id, b.Qty FROM tblMaster a JOIN tblTrans b on a.Id =b.Id WHERE Garage = 1 ) as Garage1Qty on Garage1Qty.Id = M.Id )
LEFT JOIN (  SELECT a.Id, b.Qty FROM tblMaster a JOIN tblTrans b on a.Id =b.Id WHERE Garage = 2 ) as Garage2Qty on Garage2Qty.Id = M.Id )

但它总是返回如下内容:

ID Desc  Garage1Qty  Garage2Qty  Garage3Qty  Garage4Qty
== ====  =========== =========== =========== ==========
1  Type1 1           null        null         null
1  Type1 null        3           null         null
1  Type1 null        null        2            null
2  Type2 2           null        null         null
2  Type2 null        2           null         null
2  Type2 null        null        4            null

1 个答案:

答案 0 :(得分:0)

好吧,你可以使用subquery

select ID, Desc,
       (select sum(Qty) from tblTrans where IDMaster = m.ID and Garage = 1) as Garage1Qty, 
       (select sum(Qty) from tblTrans where IDMaster = m.ID and Garage = 2) as Garage2Qty,
       (select sum(Qty) from tblTrans where IDMaster = m.ID and Garage = 3) as Garage3Qty,
       (select sum(Qty) from tblTrans where IDMaster = m.ID and Garage = 4) as Garage4Qty
from tblMaster m;       

另外,你也可以通过条件聚合

来做到这一点
select m.ID, m.Desc,
       sum(case when t.Garage = 1 then t.Qty else 0 end) as Garage1Qty,
       ...
       sum(case when t.Garage = 4 then t.Qty else 0 end) as Garage4Qty
from tblMaster m left join tblTrans t
                 on t.IDMaster = m.ID
group by m.ID, m.Desc;