首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

两列合并成一列,第一列为奇数行,第二列为偶数行的sql如何写

2012-01-20 
两列合并成一列,第一列为奇数行,第二列为偶数行的sql怎么写?如一个表如下:col1col212345678现在需要用sql

两列合并成一列,第一列为奇数行,第二列为偶数行的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

热点排行
Bad Request.