|
if object_id('pubs..tb') is not null
drop table tb
go
create table tb
(
Quarter int,
Fitem varchar(10),
Quantity int
)
insert into tb(quarter, Fitem, quantity) values(1,'A', 20)
insert into tb(quarter, Fitem, quantity) values(2,'B', 80)
insert into tb(quarter, Fitem, quantity) values(3,'A', 50)
insert into tb(quarter, Fitem, quantity) values(4,'B', 50)
select fitem,
sum(case when quarter = 1 then quantity else null end) as [1],
sum(case when quarter = 2 then quantity else null end) as [2],
sum(case when quarter = 3 then quantity else null end) as [3],
sum(case when quarter = 4 then quantity else null end) as [4]
from tb
group by Fitem
drop table tb
/*result
fitem 1 2 3 4
---------- ----------- ----------- ----------- ------- ----
A 20 NULL 50 NULL
B NULL 80 NULL 50
(The number of rows affected is 2)
*/ |
|