Click here to Skip to main content
16,004,602 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
I have one table like

SQL
create table #table1(id int,name varchar(40))
insert into #table1
select 15 id,'Global' name
union
select 16 id,'Liberty' name
union
select 17 id,'Noble' name



and i have another table like

SQL
create table #table2(number int,id int,name varchar(50))
insert into #table2
select number=1,id=15,'James Monroe'name
union
select number=2,id=15,'Cornell'name
union
select number=3,id=15,'Abraham Lincoln'name

union
select number=4,id=16,'James K. Polk'name
union
select number=5,id=16,'Roosevelt'name
union
select number=6,id=16,'George Washington'name

union
select number=7,id=17,'Woodrow Wilson'name
union
select number=8,id=17,'Andrew Jackson'name
union
select number=9,id=17,'John Adams'name



i need to print the data like this
VB
15,'Global'
3,'Abraham Lincoln'
2,'Cornell'
1,'James Monroe'
16 ,'Liberty'
6,'George Washington'
4,'James K. Polk'
5,'Roosevelt'
17,'Noble'
8,'Andrew Jackson'
9,'John Adams'
7,'Woodrow Wilson'
Posted

SQL
create table #res(number int, id int,name varchar(40))

insert into #res
	select null as number, id, name from #table1
	union
	select number, id, name from #table2

select 
	case when number is null then id else number end,
	name
from #res
order by id, number
 
Share this answer
 
This will also work:
SQL
select t2.number, t2.name from #table1 t1 left join
(
select id, name, 0 as o, id as number from #table1 union select id, name, 1 as o, number from #table2
)
t2 on t1.id=t2.id
order by t1.id, o, number desc
 
Share this answer
 
Comments
prakash.chakrala 12-Nov-13 5:25am    
i need to sort the data based on name
Zoltán Zörgő 12-Nov-13 5:31am    
Well, than change the last part with this:
order by t1.id, o, t2.name
prakash.chakrala 12-Nov-13 5:40am    
not getting the output as expected
Zoltán Zörgő 12-Nov-13 5:43am    
You should. This is what I got:
15 Global
3 Abraham Lincoln
2 Cornell
1 James Monroe
16 Liberty
6 George Washington
4 James K. Polk
5 Roosevelt
17 Noble
8 Andrew Jackson
9 John Adams
7 Woodrow Wilson

And looks like what you expect.
prakash.chakrala 12-Nov-13 5:50am    
am getting the output like
15 Global
3 Abraham Lincoln
2 Cornell
1 James Monroe
16 Liberty
6 George Washington
5 Roosevelt
4 James K. Polk
17 Noble
9 John Adams
8 Andrew Jackson
7 Woodrow Wilson

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900