22,300
社区成员




;WITH t(n,v,d) AS (
select 'n1','v1','d1' UNION
select 'n1','v2','d2' UNION
select 'n1','v3','d3' UNION
select 'n2','v4','d1' UNION
select 'n2','v5','d2' UNION
select 'n2','v6','d3' UNION
select 'n3','v7','d1' UNION
select 'n3','v8','d2'
)
SELECT * INTO #t FROM t
计算:
declare @sql varchar(max)
select @sql = isnull(@sql+',','') + 'max(case n when '''+n+''' then n else null end) as [name], max(case n when '''+n+''' then v else null end) as [value]'
from (select distinct n from #t) a
set @sql = 'select d, '+@sql+' from #t group by d'
exec(@sql)
/*
d name value name value name value
d1 n1 v1 n2 v4 n3 v7
d2 n1 v2 n2 v5 n3 v8
d3 n1 v3 n2 v6 NULL NULL
*/