两个表的复杂合并

表1                                            表2 
编号    属性1                          编号    属性2 
1      11                            1          111
1      12                            1          112
1      13                            2          221
2      21                            2          222
3      31                            4          441

将以上两个表合并成表3 
编号    属性1        属性2
1      11          111
1      12          112
1      13          null
2      21          221
2      null        222
3      31          null
4      null        441
-----------------------------------------------------------------------------------------------
declare @tb1 table(编号 int,属性1 int)
insert @tb1 select  1  ,    11
insert @tb1 select  1 ,     12 
insert @tb1 select  1 ,     13 
insert @tb1 select  2 ,     21
insert @tb1 select  3 ,     31
declare @tb2 table(编号 int,属性1 int)
insert @tb2 select  1   ,       111
insert @tb2 select  1  ,        112
insert @tb2 select  2  ,        221
insert @tb2 select  2  ,        222
insert @tb2 select  4   ,       441
select b.编号,b.属性1,属性2=c.属性1 from
(select px=(select count(1) from @tb1 where 编号=a.编号 and 属性1<=a.属性1),* from @tb1 a) b
left join
(select px=(select count(1) from @tb2 where 编号=a.编号 and 属性1<=a.属性1),* from @tb2 a ) c
on b.编号=c.编号 and b.px=c.px
union
select b.编号,c.属性1,属性2=b.属性1 from
(select px=(select count(1) from @tb2 where 编号=a.编号 and 属性1<=a.属性1),* from @tb2 a) b
left join
(select px=(select count(1) from @tb1 where 编号=a.编号 and 属性1<=a.属性1),* from @tb1 a ) c
on b.编号=c.编号 and b.px=c.px
/*
编号          属性1         属性2        
----------- ----------- -----------
1           11          111
1           12          112
1           13          NULL
2           NULL        222
2           21          221
3           31          NULL
4           NULL        441
(所影响的行数为 7 行)
*/
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值