T-Sql Pivot & Unpivot

开门见山:行转列

CREATE TABLE SALESBYQUARTER    (
YEAR INT,
QUARTER VARCHAR(2),
AMOUNT MONEY    );

SET NOCOUNT ON
    DECLARE @index INT
    DECLARE @q INT
    SET @index = 0
    DECLARE @year INT
    while (@index < 30)
    BEGIN
        SET @year = 2005 + (@index % 4)
        SET @q = (CAST((RAND() * 500) AS INT) % 4) + 1
        INSERT INTO SalesByQuarter VALUES (@year, 'Q' + CAST(@q AS CHAR(1)), RAND() * 10000.00)
        SET @index = @index + 1
    END

按以上Sql创建销售表并且插入几笔数据

实现行转列:

SELECT *FROM SALESQUARTER

PIVOT

(

SUM(AMOUNT)

FOR QUARTER IN (Q1,Q2,Q3,Q4)

)AS PVT

由于Pivot是属于Sql Server2005以上版本的属性,故请在数据库的属性->Options->Compatibility Level:Sql Server 2005(90),否则会Run Fail.

 

列转行:

create table #temptable(rowid int,colorname varchar(25),Hexa varchar(7)  
,R tinyint,G tinyint,B tinyint)   
GO  
insert into #temptable values(1,'Violet','#8B00FF',139,0,255);  
insert into #temptable values(2,'Indigo','#4B0082',75,0,130);  
insert into #temptable values(3,'Blue','#0000FF',0,0,255);  
insert into #temptable values(4,'Green','#00FF00',0,255,0);  
insert into #temptable values(5,'Yellow','#FFFF00',255,255,0);  
insert into #temptable values(6,'Orange','#FFA500',255,165,0);  
insert into #temptable values(7,'Red','#FF0000',255,0,0);  
GO  
select * from #temptable  
GO 

按照以上Sql创建临时表,并插入数据

SELECT *FROM (SELECT *FROM #TEMPTABLE) P

UNPIVOT

(RGBVALUE FOR RGB IN(R,G,B)) AS UPVT;

 

你可能感兴趣的:(t-sql)