日期:2014-05-17  浏览次数:20642 次

横向合并两个表
例如:
表1
name id
张三 1
张三 2 
张三 3
表2
name object name
张三 AL
张三 BL
张三 CL
我想得到的结果是把id和object name合并,其中id是自增变量
 id object name
  1 AL
  2 BL
  3 CL

------解决方案--------------------
两个表没有连接关系
我们来给他创一个联系
--构建示例数据
create table 表1(name varchar(20), id int)
insert into 表1
select '张三', 1 union 
select '张三', 2 union
select '张三', 3 
create table 表2(name varchar(20), objectname varchar(20))
insert into 表2
select '张三', 'AL' union 
select '张三', 'BL' union
select '张三', 'CL' 
--解决方案
;with cet1 as
(select *,row_number()over(order by id) rn from 表1
),
cet2 as
(select *,row_number()over(order by objectname) rn from 表2
)
select a.id,b.objectname from cet1 a,cet2 b where a.rn = b.rn

/*
id objectname
----------- --------------------
1 AL
2 BL
3 CL

(3 行受影响)

*/