sql关于动态行转列的分支问题。谢谢知道的告知小弟

aspdontnet 2009-12-29 12:01:11
现通过连接查询查询出结果
entityname fzr
线路电气 李瓜
线路结构 王威
电气一次 肖飞
技经 尹豫落
电气二次 李选正
通信 许杰

需要这种效果
n1 e1 n2 e2 n3 n3
李瓜 线路电气 王威 线路结构 肖飞 电气一次 ----------------------------

依次显示。

因为不是静态的,而entityname 有未知的个数。。fzr 对应entityname
求各位大侠帮帮小弟!
...全文
100 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
aspdontnet 2009-12-29
  • 打赏
  • 举报
回复
感谢各位大侠。。我先结贴
woainili__ 2009-12-29
  • 打赏
  • 举报
回复
if object_id('[tb]') is not null drop table [tb]
create table [tb]([entityname] varchar(8),[fzr] varchar(6))
insert [tb]
select '线路电气','李瓜' union all
select '线路结构','王威' union all
select '电气一次','肖飞' union all
select '技经','尹豫落' union all
select '电气二次','李选正' union all
select '通信','许杰'

select identity(int,1,1) as id,* into #temp from [tb]

declare @sql varchar(8000)

select @sql = isnull(@sql,'')+',max(case id when '+ltrim(id)+' then fzr else '''' end) as [n'+ltrim(id)+']
,max(case id when '+ltrim(id)+' then entityname else '''' end) as [e'+ltrim(id)+']'
from #temp

select @sql = 'select '+stuff(@sql,1,1,'')+' from #temp'

exec(@sql)

drop table #temp
-----------------------
李瓜 线路电气 王威 线路结构 肖飞 电气一次 尹豫落 技经 李选正 电气二次 许杰 通信

nianran520 2009-12-29
  • 打赏
  • 举报
回复
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
create table [tb]([entityname] varchar(8),[fzr] varchar(6))
insert [tb]
select '线路电气','李瓜' union all
select '线路结构','王威' union all
select '电气一次','肖飞' union all
select '技经','尹豫落' union all
select '电气二次','李选正' union all
select '通信','许杰'

select identity(int,1,1) as id,* into #temp from [tb]

declare @sql varchar(8000)

select @sql = isnull(@sql,'')+',max(case id when '+ltrim(id)+' then fzr else '''' end) as [n'+ltrim(id)+']
,max(case id when '+ltrim(id)+' then entityname else '''' end) as [e'+ltrim(id)+']'
from #temp

select @sql = 'select '+stuff(@sql,1,1,'')+' from #temp'

exec(@sql)

drop table #temp
-----------------------
李瓜 线路电气 王威 线路结构 肖飞 电气一次 尹豫落 技经 李选正 电气二次 许杰 通信
--小F-- 2009-12-29
  • 打赏
  • 举报
回复
这个 准备写晕
playwarcraft 2009-12-29
  • 打赏
  • 举报
回复
除非你查出的资料笔数不多,否则。。。。。。
Yang_ 2009-12-29
  • 打赏
  • 举报
回复
这是不合理的,字段个数和长度是有限制的
dawugui 2009-12-29
  • 打赏
  • 举报
回复
两个两个一组,还是...?

最好给出完整的表结构,测试数据,计算方法和正确结果.


发帖注意事项
http://topic.csdn.net/u/20091130/21/fb718680-98ff-4afb-98d8-cff2f8293ed5.html?24281

34,590

社区成员

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

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