zoukankan      html  css  js  c++  java
  • 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;


    Impossible = I'm possible
    Don't be the same, be better. Just do it.
    You'll be there.
  • 相关阅读:
    iOS 代码让手机震动一下
    iOS开发 --制作圆形的头像(UIImage)
    JAVA基本数据类型和引用数据类型的区别
    jquery基础
    JS基础
    JAVA异常详解
    单例模式详解及java常用类
    JAVA基础之字符串和面向对象
    我的第一篇博客 初识动画,飞机行小动画
    GCD系列:调度组(dispatch_group)
  • 原文地址:https://www.cnblogs.com/gavin-king/p/4661556.html
Copyright © 2011-2022 走看看