T-SQL Pivot & Unpivot

Source: Internet
Author: User
Tags rand

Go straight: Row to Column

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 () *) as INT)% 4) + 1
INSERT into Salesbyquarter VALUES (@year, ' Q ' + CAST (@q as CHAR (1)), RAND () * 10000.00)
SET @index = @index + 1
END

Create a sales table from the SQL above and insert a few data

To implement row-to-column:

SELECT *from Salesquarter

PIVOT

(

SUM (AMOUNT)

For QUARTER in (Q1,Q2,Q3,Q4)

) as PVT

Because pivot is a property of Sql Server2005 or later, the properties of the database->options->compatibility level:sql Server 2005 (90), otherwise run fail.

List of career change:

CREATE TABLE #temptable (rowid int,colorname varchar), 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

Create a temporary table with the above SQL and insert the data

Select *from (select *from #TEMPTABLE) P

UNPIVOT

(Rgbvalue for RGB in (R,G,B)) As UPVT;

T-SQL Pivot & Unpivot

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.