日期:2014-05-16 浏览次数:20569 次
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+item1+'=sum(case when [item1]='+quotename(item1,'''')+' then no1 else 0 end)'+','
+quotename(item1 )+'=sum(case when [item1]='+quotename(item1,'''')+' then no2 else 0 end)'
from t1 group by item1
print @s
exec('select id'+@s+' from t1 group by [id]')
create table ch
(ID int,Item1 varchar(5),Number1 int,Number2 int)
insert into ch
select 1,'A',10,1 union all
select 1,'B',5,3 union all
select 1,'A',3,2 union all
select 2,'A',5,3 union all
select 2,'B',1,2 union all
select 2,'B',2,2
select ID,[A(Number1)],[A(Number2)],[B(Number1)],[B(Number2)]
from
(select ID,Item1+'('+c+')' 'c',v
from
(select ID,Item1,sum(Number1) 'Number1',sum(Number2) 'Number2'
from ch
group by ID,Item1) a
unpivot(v for c in([Number1],[Number2])) u) b
pivot(max(v) for c in([A(Number1)],[A(Number2)],[B(Number1)],[B(Number2)])) p
/*
ID A(Number1) A(Number2) B(Number1) B(Number2)
----------- ----------- ----------- ----------- -----------
1 13 3 5 3
2 5 3 3 4
(2 row(s) affected)
*/