该死的交叉表

coffeewar 2004-07-20 09:45:19
表内容:
x y

1 a
1 b
1 c
1 d
1 e
1 f
1 g
2 c
2 d
2 g
如何转换成:
p P1 P2 P3 P4 P5

1 a b c d e
2 c d g null null

谢谢!
...全文
233 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
coffeewar 2004-07-21
  • 打赏
  • 举报
回复
每次都能及时得到你的帮助,非常感谢!
fengyaner 2004-07-21
  • 打赏
  • 举报
回复
就是厉害
zjcxc 元老 2004-07-20
  • 打赏
  • 举报
回复
--如果不满足每组x,y唯一的条件,就用临时表:
declare @s varchar(8000),@i int
select @s='',@i=max(ii)
from(select ii=count(*) from 表 group by x)a
while @i>0
select @s=',P'+cast(@i as varchar)+'=max(case id when '
+cast(@i as varchar)+' then y end)'+@s
,@i=@i-1
exec('
select id=identity(int,1,1),* into #t from 表
select p=x'+@s+'
from(
select x,y,id=(select count(*) from #t where x=a.x and id<=a.id)
from #t a
)a group by x')
zjcxc 元老 2004-07-20
  • 打赏
  • 举报
回复
--测试

--测试数据
create table 表(x int,y varchar(10))
insert 表 select 1,'a'
union all select 1,'b'
union all select 1,'c'
union all select 1,'d'
union all select 1,'e'
union all select 1,'f'
union all select 1,'g'
union all select 2,'c'
union all select 2,'d'
union all select 2,'g'
go

--查询
declare @s varchar(8000),@i int
select @s='',@i=max(ii)
from(select ii=count(*) from 表 group by x)a
while @i>0
select @s=',P'+cast(@i as varchar)+'=max(case id when '
+cast(@i as varchar)+' then y end)'+@s
,@i=@i-1
exec('select p=x'+@s+'
from(
select *,id=(select count(*) from 表 where x=a.x and y<=a.y)
from 表 a
)a group by x')


go

--删除测试
drop table 表

/*--测试结果

p P1 P2 P3 P4 P5 P6 P7
----- ---- ---- ---- ---- ---- ---- -----
1 a b c d e f g
2 c d g NULL NULL NULL NULL

--*/
zjcxc 元老 2004-07-20
  • 打赏
  • 举报
回复
--少写了一部分东西
declare @s varchar(8000),@i int
select @s='',@i=max(ii)
from(select ii=count(*) from 表 group by x)a
while @i>0
select @s=',P'+cast(@i as varchar)+'=max(case id when '
+cast(@i as varchar)+' then y end)'+@s
,@i=@i-1
exec('select p=x'+@s+'
from(
select *,id=(select count(*) from 表 where x=a.x and y<=a.y)
from 表 a
)a group by x')
zjcxc 元老 2004-07-20
  • 打赏
  • 举报
回复
--如果对于每一组x,y列的值不重复,可以用:

declare @s varchar(8000),@i int
select @s='',@i=max(ii)
from(select ii=count(*) from 表 group by x)a
while @i>0
select @s=',P'+cast(@i as varchar)+'=max(case id when '
+cast(@i as varchar)+' then y end)'+@s
,@i=@i-1
exec('select p=x'+@s+' from 表 group by x')

34,590

社区成员

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

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