如何通过公共列组合两个结果集?

时间:2017-05-25 20:48:51

标签: sql-server

我觉得应该有一个简单的方法来做到这一点。

给定两个表(ID是主键,没有重复):

 TblQtyNew            TblQtyUsed

ID | QtyNew          ID | QtyUsed
1    15              1    7
2    18              3    21

如何获得以下结果?

ID | QtyNew | QtyUsed
1    15        7
2    18        NULL
3    NULL      21

我提出的唯一解决方案涉及ID列上的UNION,然后是两个左连接:

(SELECT ID FROM TblQtyNew) UNION (SELECT ID FROM TblQtyUsed) as IDs
LEFT JOIN
(SELECT QtyNew FROM TblQtyNew) ON TblQtyNew.ID = IDs.ID
LEFT JOIN
(SELECT QtyUsed FROM TblQtyUsed) ON TblQtyUsed.ID = IDs.ID

有更简单的方法吗?

6 个答案:

答案 0 :(得分:1)

您需要FULL OUTER JOIN

SELECT COALESCE(T1.ID,T2.ID) as ID, T1.QtyNew, T2.QtyUsed
FROM TblQtyNew T1
FULL OUTER JOIN TblQtyUsed T2 on T1.ID = T2.ID

答案 1 :(得分:1)

使用FULL JOINCase

DECLARE @T1 TABLE (id int , QtyNew  int);
DECLARE @T2 TABLE( id int , QtyUsed int);

insert into @T1 values (1,15),(2,18);
insert into @T2 values (1,7),(3,21);

SELECT ID = case when T1.ID IS not Null then T1.ID else T2.ID end, T1.QtyNew, T2.QtyUsed
FROM  @T1 T1
full JOIN  @T2 T2 on T1.ID = T2.ID
Order by ID;

Demo

答案 2 :(得分:1)

1

SELECT ID,SUM(ISNULL(QtyNew)) AS QtyNew,SUM(ISNULL(QtyUsed)) AS QtyUsed
FROM (
    SELECT ID,QtyNew,NULL AS QtyUsed  FROM TblQtyNew
    UNION ALL
    SELECT ID,NULL QtyNew, QtyUsed FROM TblQtyUsed
) AS t
GROUP BY ID

2

SELECT COALESCE(n.ID,U.ID) AS ID,n.QtyNew,u.QtyUsed
FROM TblQtyNew AS n FULL OUTER JOIN TblQtyUsed AS u ON n.ID=u.ID

答案 3 :(得分:1)

您可以在ID中使用完全加入和合并,如下所示:

select coalesce(t1.id,t2.id) as Id, Qtynew, QtYused 
    from #table1 t1 full join #table2 t2
    on t1.id = t2.id

输出:

    +----+--------+---------+
    | Id | Qtynew | QtYused |
    +----+--------+---------+
    |  1 | 15     | 7       |
    |  2 | 18     | NULL    |
    |  3 | NULL   | 21      |
    +----+--------+---------+

答案 4 :(得分:1)

我故意尝试替代方法。

declare @TblQtyNew  table (ID int,QtyNew int)
insert into @TblQtyNew VALUES
(1,15)           
,(2,18)

  declare @TblQtyUsed  table ( ID int, QtyUsed int)
  insert into @TblQtyUsed VALUES
 (1 ,7 )
 ,(3 ,21)   

 ;with CTE as
 (
 select a.id,QtyNew,b.QtyUsed from @TblQtyNew a
inner join @TblQtyUsed b on a.id=b.ID
)
select * from CTE
union all
select  a.id,QtyNew,null
from @TblQtyNew a
where not exists(select id from cte c where c.id=a.id)

union all
select  a.id,null,QtyUsed
from  @TblQtyUsed a
where not exists(select id from cte c where c.id=a.id)

答案 5 :(得分:0)

select Id, QtyNew, QtyUsed
from TblQtyNew Full outer join TblQtyUsed
on TblQtyNew.ID=TBLQtyUsed.ID