将主从数据行转成列(有难度)

shine888 2008-03-28 10:49:40
举例说明
主键 名称 父级ID
1 中国
2 广东 1
3 深圳 2

转换后的结果
第一级 第二级 第三级
中国 广东 深圳

级数是不固定的,有请高人解决。谢谢
...全文
91 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
海上明月-念 2010-10-22
  • 打赏
  • 举报
回复


接3# 用Pivot 函数实现,不过这个也是只能固定级别的。
select * from
(
select Name ,Pid from tb
) as A
pivot
(max(Name) for A.PID in ([1],[2],[3],[4],[5],[6],[7],[8])) as B
shine888 2008-03-28
  • 打赏
  • 举报
回复
固定的比较容易一点,但级数有可能不一定的情况下只能用2005解决吗??
viva369 2008-03-28
  • 打赏
  • 举报
回复
动态比较麻烦,要用2005里的pivote
wzy_love_sly 2008-03-28
  • 打赏
  • 举报
回复
create table tb(id int,name varchar(20),PID int,c int)
insert into tb select 1,'中国',null,0
insert into tb select 2,'广东',1,1
insert into tb select 3,'深圳',2,2
insert into tb select 4,'河北',1,1
insert into tb select 5,'秦皇岛',4,2
insert into tb select 6,'山海关',5,3

select one.name as '第一级',two.name as '第二级',thr.name as '第三级',fou.name as '第四级' from
(select * from tb where c=0) one left join
(select * from tb where c=1) two on one.id=two.pid left join
(select * from tb where c=2) thr on two.id=thr.pid left join
(select * from tb where c=3) fou on thr.id=fou.pid


第一级 第二级 第三级 第四级
中国 广东 深圳 NULL
中国 河北 秦皇岛 山海关

动态的有点麻烦
shine888 2008-03-28
  • 打赏
  • 举报
回复
没有用过,请高人详细指点。谢谢
青锋-SS 2008-03-28
  • 打赏
  • 举报
回复
行列转换可以参考Huang族的代码.
ojuju10 2008-03-28
  • 打赏
  • 举报
回复

3楼的已经帮你解决啦
shine888 2008-03-28
  • 打赏
  • 举报
回复
还有哪位高人解答一下吗??谢谢

34,587

社区成员

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

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