sql 合并列

aplesen 2010-08-30 08:58:49
数据库是sql server2005的,
有表 Table_20100830 如下:
tid tname tcount1 tcount2
1 奔驰 1 2
2 宝马 2 3
3 福特 5 NULL
4 本田 NULL 5
我需要得到如下结果:
tid tname tcount
1 奔驰 1
1 奔驰 2
2 宝马 2
2 宝马 3
3 福特 5
4 本田 5
请问这个sql语句该如何写,小弟在线等
...全文
505 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
aplesen 2010-08-30
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 sinpoal 的回复:]
SQL code

Select [tid],[tname],[tcount1] from tb where [tcount1] is not null
union all
Select [tid],[tname],[tcount2] from tb where [tcount2] is not null
order by tid



[/Quote]
sinpoal 2010-08-30
  • 打赏
  • 举报
回复


Select [tid],[tname],[tcount1] from tb where [tcount1] is not null
union all
Select [tid],[tname],[tcount2] from tb where [tcount2] is not null
order by tid


DEATH64 2010-08-30
  • 打赏
  • 举报
回复
SELECT tid ,tname ,tcount
FROM #MyTable
UNPIVOT
(
tcount FOR BH IN ([tcount1],[tcount2])
) Y

没测试,看看行不行.
水族杰纶 2010-08-30
  • 打赏
  • 举报
回复
if not object_id('tb') is null
drop table tb
Go
Create table tb([tid] int,[tname] nvarchar(2),[tcount1] int,[tcount2] int)
Insert tb
select 1,N'奔驰',1,2 union all
select 2,N'宝马',2,3 union all
select 3,N'福特',5,null union all
select 4,N'本田',null,5
Go
Select [tid],[tname],[tcount1] from tb where [tcount1] is not null
union all
Select [tid],[tname],[tcount2] from tb where [tcount2] is not null
order by tid
/*
tid tname tcount1
----------- ----- -----------
1 奔驰 1
1 奔驰 2
2 宝马 3
2 宝马 2
3 福特 5
4 本田 5

(6 個資料列受到影響)
*/
PxxxP 2010-08-30
  • 打赏
  • 举报
回复
没看明白什么规律?
aplesen 2010-08-30
  • 打赏
  • 举报
回复
怎么没人回答呢?

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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