SQL SERVER TUTORIAL IN DEPTH

The blog is to help users about sql server

Others

LightBlog

Breaking

Saturday 4 January 2014

Joining Two Tables without any Common Column between them



create table #temp1
(
id int,
username varchar(50)
)

create table #temp2
(
  
  age int,
  sex varchar(1)

)

insert into #temp1
select 1,'anurag'
union all select 2,'abhi'
union all select 3,'binda'
union all select 4,'asu'

insert into #temp2
select 24,'m'
union all select 22,'m'
union all select 25,'m'

select * from #temp1
select * from #temp2

----------------Now we have to combine the two table ..lets try..-----------------

;with cte(id,username,row1)
as
(
select id,username,row_number() over (order by id)
from #temp1
),
cte1(age,sex,row2)
as
(
select age,sex,row_number() over (order by age)
from #temp2
),
cte2
as
(
select c1.id,c1.username,c2.age,c2.sex
from cte c1
left join cte1 c2 on c1.row1=c2.row2
)
select * from cte2
-----------------------------------------------------------------------------------






No comments:

Post a Comment

 test