两列数据合并到一列中

drik 2009-03-10 10:12:57
我的表有三列,我想将其中两列数据合并到一列中

A B C
a 1 31
b 2 32
a 3 33
以此类推
我想得到如下结果
D列
a
b
c
1
2
3
如何写这个SQL语句,谢谢
...全文
432 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Veronika 2010-02-10
  • 打赏
  • 举报
回复
还要求回帖,只能回帖之后再看看
kye_jufei 2009-03-10
  • 打赏
  • 举报
回复

create table tb(A varchar(10), B int, C int)
insert into tb values('a' , 1 , 31 )
insert into tb values('b' , 2 , 32 )
insert into tb values('a' , 3 , 33 )
go

select cast(a as varchar) d from tb
union all
select cast(b as varchar) d from tb

drop table tb


/*
d
----------
a
b
a
1
2
3
*/

yuyangyangde 2009-03-10
  • 打赏
  • 举报
回复


create table A(a1 varchar(20),a2 varchar(20))
insert into A values('a','1')
insert into A values('b','2')
insert into A values('c','3')



create Table B(B1 varchar(20))
insert into B
select a1
from A
insert into B
select a2
from A
select * from B


--
a
b
c
1
2
3
肥龙上天 2009-03-10
  • 打赏
  • 举报
回复
[Quote=引用楼主 drik 的帖子:]
我的表有三列,我想将其中两列数据合并到一列中

A B C
a 1 31
b 2 32
a 3 33
以此类推
我想得到如下结果
D列
a
b
c
1
2
3
如何写这个SQL语句,谢谢
[/Quote]



create table #1(A varchar(10), B int, C int)
insert into #1 values('a' , 1 , 31 )
insert into #1 values('b' , 2 , 32 )
insert into #1 values('a' , 3 , 33 )
go
-----如果列中不能包含重复值
select rtrim(a) D from #1
union
select rtrim(b) from #1
/*
D
------------
1
2
3
a
b

(5 row(s) affected)

*/

------如果列中可以包含重复值
select rtrim(a) D from #1
union all
select rtrim(b) from #1
/*
D
------------
a
b
a
1
2
3

(6 row(s) affected)
*/
dawugui 2009-03-10
  • 打赏
  • 举报
回复
--如果类型不一样,都转换为varchar

create table tb(A varchar(10), B int, C int)
insert into tb values('a' , 1 , 31 )
insert into tb values('b' , 2 , 32 )
insert into tb values('a' , 3 , 33 )
go

select cast(a as varchar) d from tb
union all
select cast(b as varchar) d from tb

drop table tb


/*
d
----------
a
b
a
1
2
3
*/
dawugui 2009-03-10
  • 打赏
  • 举报
回复
create table tb(A varchar(10), B varchar(10), C int)
insert into tb values('a' , '1' , 31 )
insert into tb values('b' , '2' , 32 )
insert into tb values('a' , '3' , 33 )
go

select a d from tb
union all
select b d from tb

drop table tb


/*
d
----------
a
b
a
1
2
3
*/
liangCK 2009-03-10
  • 打赏
  • 举报
回复
SELECT A FROM tb
UNION ALL
SELECT RTRIM(B) FROM tb
天-笑 2009-03-10
  • 打赏
  • 举报
回复



select a ,b, c ,a as d from table
union all
select a ,b, c ,b as d from table



dawugui 2009-03-10
  • 打赏
  • 举报
回复
select a from tb
union all
select b from tb

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧