行转列老问题?

ma_yan_jun_78 2008-03-25 10:33:01

create table Tb(id int,iid bigint)
insert into Tb
select 1,1
union all select 1,2
union all select 1,3
--.....n
union all select 2,1
union all select 2,2
union all select 2,3
--......n

我想要的结果:
id , iid1,iid2,iid3,iidn
1 1 2 3 n
2 1 2 3 n

declare @s varchar(8000)
select @s=' select id'
select @s=@s+',[技能'+cast([iid] as varchar) +']=case [iid] when '+ cast([iid] as varchar)+' then iid end'

from a
exec (@s+' from a ')
我的代码与我相的结果不符,请各们朋友帮我解决一下,谢谢!
...全文
58 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
gahade 2008-03-25
  • 打赏
  • 举报
回复
看回复专用
$扫地僧$ 2008-03-25
  • 打赏
  • 举报
回复
create table Tb(id int,iid bigint)
insert into Tb
select 1,1
union all select 1,2
union all select 1,3
--.....n
union all select 2,1
union all select 2,2
union all select 2,3




declare @T_SQL varchar(8000)
set @T_SQL=''
select @T_SQL=@T_SQL + ' Max(case when iid=' + cast(iid as varchar) + 'then iid else 0 end) as iid' +cast(iid as varchar) +',' from (select DISTINCT iid from Tb) T
set @T_SQL=left(@T_SQL,len(@T_SQL)-1)
set @T_SQL='select id,' + @T_SQL + ' from Tb group by id'
exec (@T_SQL)
gahade 2008-03-25
  • 打赏
  • 举报
回复

create table Tb(id int,iid bigint)
insert into Tb
select 1,1
union all select 1,2
union all select 1,3
union all select 2,1
union all select 2,2
union all select 2,3

declare @s varchar(8000)
set @s=''
select @s=@s+',max(case when iid='+rtrim(iid)+' then iid else 0 end) as [iid'+rtrim(iid)+']'
from (select distinct iid from Tb)t
exec('select id'+@s+' from Tb group by id')
/*
id iid1 iid2 iid3
----------- -------------------- -------------------- --------------------
1 1 2 3
2 1 2 3
*/

34,837

社区成员

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

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