日期:2014-05-18  浏览次数:20499 次

两列合并成一列,第一列为奇数行,第二列为偶数行的sql怎么写?
如一个表如下:
col1         col2
1                 2
3                 4
5                 6
7                 8
现在需要用sql查询出如下的结果:
col1
1
2
3
4
5
6
7
8
怎么实现?

------解决方案--------------------
create table test(col1 int,col2 int)
insert test select 1,2
union all select 3,4
union all select 5,6
union all select 7,8

select col=col1 from test
union all select col2 from test
order by col

drop table test

/*
col
-----------
1
2
3
4
5
6
7
8

(所影响的行数为 8 行)
*/
------解决方案--------------------
----------------------------
create table #tmp(col1 int,col2 int)
insert #tmp values(1,2)
insert #tmp values(3,4)
insert #tmp values(5,6)
insert #tmp values(7,8)
select col1 from #tmp
union all
select col2 from #tmp
order by col1
drop table #tmp
返回:
col1
-----------
1
2
3
4
5
6
7
8
------解决方案--------------------
--用union all

select *
from
(
select col1 from 表名
union all
select col2 from 表名
) as t
order by col1

------解决方案--------------------
字符串也可以排序啊,楼主再补充下数据和想要的结果
------解决方案--------------------
select *
from
(
select col1 from 表名
union all
select col2 from 表名
) as t
order by cast(col1 as int) --如果字符串都是数字,转换一下


------解决方案--------------------
--表中加唯一字段ID


select *
from
(
select id, col1, 1 as xh from 表名
union all
select id, col2, 2 as xh from 表名
) as t
order by id,xh