SQL Server:从具有唯一数据的多个表连接

时间:2015-03-30 03:04:23

标签: sql join sql-server-2008-r2 unique

我有3张这样的桌子。

表1

ID  ClaimNo Data1
1   1   EC11
2   1   EC12
4   2   EC21

表2

ID  ClaimNo Data2
1   1   IWC11
3   2   IWC21
4   2   IWC22
5   2   IWC23

表3

ID  ClaimNo Data3
1   1   DC11
2   1   DC12
3   1   DC13
4   1   DC14
5   1   DC15

我想有这样的事情:

ClaimNo Data1   Data2   Data3
------------------------------
   1    EC11    IWC11   DC11
   1    EC12            DC12
   1                    DC13
   1                    DC14    
   1                    DC15
   2    EC21    IWC21   
   2            IWC22   
   2            IWC23

任何人都可以帮我查询一下。

2 个答案:

答案 0 :(得分:0)

您似乎想要在列中组织数据。问题是该表没有加入的密钥。幸运的是,row_number()提供了一种解决方案 - 您可以为连接生成序列号。

然后,您想要的联接是full outer join - 因为您不知道哪个表格的列表最长。使用coalesce()有一些额外的逻辑,以确保table3中的行与前两个表匹配:

select coalesce(t1.claimno, t2.claimno, t3.claimno) as claimno,
       t1.data as data1, t2.data as data2, t3.data as data3
from (select t1.*, row_number() over (partition by claimno order by id) as seqnum
      from table1 t1
     ) t1 full outer join
     (select t2.*, row_number() over (partition by claimno order by id) as seqnum
      from table1 t2
     ) t2 full outer join
     on t2.seqnum = t1.seqnum and t1.claimno = t2.claimno
     (select t3.*, row_number() over (partition by claimno order by id) as seqnum
      from table1 t3
     ) t3
     on t3.claimno = coalesce(t1.claimno, t2.claimno) and
        t3.seqnum = coalesce(t1.seqnum, t2.seqnum)

答案 1 :(得分:0)

感谢您的支持。看来我们没有直接的答案。我想我可以运行以下查询临时数据



select T1.ClaimNo, 
	   T1.Data1, ROW_NUMBER() OVER(PARTITION BY Data1 ORDER BY Data1) AS Data1Rk, 
	   T2.Data2, ROW_NUMBER() OVER(PARTITION BY Data2 ORDER BY Data2) AS Data2Rk,
	   T3.Data3, ROW_NUMBER() OVER(PARTITION BY Data3 ORDER BY Data3) AS Data3Rk
from (Table1 T1 left join Table2 T2 on T1.ClaimNo=T2.ClaimNo) left join Table3 T3 on T1.ClaimNo=T3.ClaimNo




这是结果集



ClaimNo	Data1	Data1Rk	Data2	Data2Rk	Data3	Data2Rk
2	EC21	1	IWC21	1	NULL	1
2	EC21	2	IWC22	1	NULL	2
2	EC21	3	IWC23	1	NULL	3
1	EC11	1	IWC11	1	DC11	1
1	EC12	1	IWC11	6	DC11	2
1	EC12	2	IWC11	7	DC12	1
1	EC11	2	IWC11	2	DC12	2
1	EC11	3	IWC11	3	DC13	1
1	EC12	3	IWC11	8	DC13	2
1	EC12	4	IWC11	9	DC14	1
1	EC11	4	IWC11	4	DC14	2
1	EC11	5	IWC11	5	DC15	1
1	EC12	5	IWC11	10	DC15	2




然后我通过rk = 1过滤结果而不是空数据