Try this out:
DECLARE @Table table (
Col1 char(1),
Col2 varchar(6),
Col3 smallint
)
;
insert @Table
values
('A','before',100),
('A','after',10),
('A','after',80),
('B','before',280),
('B','before',20),
('B','after',250),
('C','before',150),
('C','after',220)
;
With groups (Col1, Col2, Col3) as (
select Col1, Col2, sum(Col3) AS Col3
from @Table
group by Col1, Col2
)
select Col1, Col2, Amt
from (
select '1' as Seq, Col1, Col2, Col3 as Amt from Groups where Col2 = 'before'
union all
select '2' as Seq, Col1, Col2, Col3 as Amt from Groups where Col2 = 'after'
union all
select '3' as Seq, B.Col1, 'Diff' as Col2, B.Col3 - A.Col3 as Amt
from Groups B
inner join Groups A on B.Col1 = A.Col1
where B.Col2 = 'before'
and A.Col2 = 'after'
) r
order by Col1, Seq