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)
*/