ʹÓùýSQL Server 2000µÄÈ˶¼ÖªµÀ£¬ÒªÏëʵÏÖÐÐÁÐת»»,±ØÐë×ÛºÏÀûÓþۺϺ¯ÊýºÍ¶¯Ì¬SQL£¬¾ßÌåʵÏÖÆðÀ´ÐèÒªÒ»¶¨µÄ¼¼ÇÉ£¬¶øÔÚSQL Server 2005ÖУ¬Ê¹ÓÃÐÂÒý½øµÄ¹Ø¼ü×ÖPIVOT/UNPIVOT£¬Ôò¿ÉÒÔºÜÈÝÒ×µÄʵÏÖÐÐÁÐת»»µÄÐèÇó¡£
ÔÚ±¾ÎÄÖÐÎÒÃǽ«Í¨¹ýÁ½¸ö¼òµ¥µÄÀý×ÓÏêϸ½²½âPIVOT/UNPIVOTµÄÓ÷¨¡£
PIVOTµÄÓ÷¨£º
Ê×ÏÈ´´½¨²âÊÔ±í£¬È»ºó²åÈë²âÊÔÊý¾Ý
create table test(id int,name varchar(20),quarter int,profile int)
insert into test values(1,'a',1,1000)
insert into test values(1,'a',2,2000)
insert into test values(1,'a',3,4000)
insert into test values(1,'a',4,5000)
insert into test values(2,'b',1,3000)
insert into test values(2,'b',2,3500)
insert into test values(2,'b',3,4200)
insert into test values(2,'b',4,5500)
select * from test
id name quarter profile
----------- -------------- ----------- -----------
1 a 1 1000
1 a 2 2000
1 a 3 4000
1 a 4 5000
2 b 1 3000
2 b 2 3500
2 b 3 4200
2 b 4 5500
(8 row(s) affected)
ʹÓÃPIVOT½«Ëĸö¼¾¶ÈµÄÀûÈóת»»³ÉºáÏòÏÔʾ:
select id,name,
[1] as "Ò»¼¾¶È",
[2] as "¶þ¼¾¶È",
[3] as "Èý¼¾¶È",
[4] as "Ëļ¾¶È"
from
test
pivot
(
sum(profile)
for quarter in
([1],[2],[3],[4])
)
as pvt
id name Ò»¼¾¶È ¶þ¼¾¶È Èý¼¾¶È Ëļ¾¶È
-------- --------- ----------- -------- ------- -------
1 a 1000 2000 4000 5000
2 b 3000 3500 4200 5500
(2 row(s) affected)
UNPIVOTµÄÓ÷¨£º
Ê×ÏȽ¨Á¢²âÊÔ±í£¬È»ºó²åÈë²âÊÔÊý¾Ý
drop table test
create table test(id int,name varchar(20), Q1 int, Q2 int, Q3 int, Q4 int)
insert into test values(1,'a',1000,2000,4000,5000)
insert into test values(2,'b',3000,3500,4200,5500)
select * from test
id name Q1 Q2 Q3 Q4
-------- ------- --------- --------- -------- --------
1 a 1000 2000 4000 5000
2 b 3000 3500 4200 5500
(2 row(s) affected)
ʹÓÃUNPIVOT£¬½«Í¬Ò»ÐÐÖÐËĸö¼¾¶ÈµÄÁÐÊý¾Ýת»»³ÉËÄÐÐÊý¾Ý£º
select id,name,quarter,profile
from
test
unpivot
(
profile
for quarter in
([Q1],[Q2],[Q3],[Q4])
)
as unpvt
id name quarter profile
----------- ----------- ----