27,579
社区成员
发帖
与我相关
我的任务
分享
给你份:
--建立测试环境
Create Table 表(Item_ID varchar(10),sel varchar(10))
--插入数据
--注意下面Item_ID这个字段,这是进行分组的,可以自己进行测试下,把2都改成1
insert into 表
select '1','张三' union
select '1','李四' union
select '1','王五' union
select '2','赵六' union
select '2','老七'
--测试语句
select id=identity(int),* into #tt from 表
select item_id,sel,orderId=cast((select count(*) from #tt where item_id=a.item_id and id<=a.id) as char(1))
into #t from #tt a
DECLARE @SQL VARCHAR(8000)
SET @SQL='SELECT item_id'
SELECT @SQL= @SQL+ ',MIN(CASE WHEN orderId = ''' + orderId + ''' THEN sel END) [数据' + orderId + ']' FROM (SELECT DISTINCT orderId FROM #T) A
SET @SQL=@SQL+' FROM #t GROUP BY item_id'
exec (@SQL)
drop table #t
drop table #tt
--删除测试环境
Drop Table 表
go
/*
1 李四 王五 张三
2 老七 赵六 NULL*/
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (name nvarchar(4))
insert into [TB]
select '张三' union all
select '李四' union all
select '王五'
select * from [TB]
select distinct [name]=stuff((select ','+[name] from tb for xml path('')), 1, 1, '')
from tb
/*
张三,李四,王五*/