• 特殊的交叉报表处理示例.sql


    CREATE TABLE tb(Item varchar(10),Color varchar(10),Quantity int)
    INSERT tb SELECT 'Table','Blue',  124
    UNION ALL SELECT 'Table','Red',   60
    UNION ALL SELECT 'Table','Red',   99
    UNION ALL SELECT 'Table','Green', 120
    UNION ALL SELECT 'Table','Green', 110
    UNION ALL SELECT 'Chair','Yellow',101
    UNION ALL SELECT 'Chair','Yellow',131
    UNION ALL SELECT 'Chair','Red',   90
    UNION ALL SELECT 'Chair','White', 55
    GO

    --生成分组信息临时表
    SELECT Item,Color,id=0
    INTO # FROM tb
    GROUP BY Item,Color
    --生成各组Item的Color序号
    DECLARE @Item varchar(10),@i varchar(10)
    UPDATE # SET
        @i=CASE WHEN @Item=Item THEN @i+1 ELSE 1 END,
        id=@i,@Item=Item

    --生成交叉数据报表处理语句
    DECLARE @s1 nvarchar(4000),@s2 nvarchar(4000),@fd nvarchar(4000)
    SELECT @s1='',@s2='',@fd='',@i=MAX(id)
    FROM #
    GROUP BY Item
    WHILE @i>0
        SELECT
            @fd=','+QUOTENAME('col'+@i)+'='+QUOTENAME(@i)+@fd,
            @s1=@s1+','+QUOTENAME(@i)
                +'=MAX(CASE id WHEN '+@i
                +' THEN Color END)',
            @s2=@s2+','+QUOTENAME(@i)
                +'=CAST(SUM(CASE b.id WHEN '+@i
                +' THEN a.Quantity END) as varchar)',
            @i=@i-1
    EXEC('
    SELECT Item=Item'+@fd+' FROM(
        SELECT Item'+@s1+',s=0 FROM # GROUP BY Item
        UNION ALL
        SELECT a.Item'+@s2+',s=1
        FROM tb a,# b
        WHERE a.Item=b.Item AND a.Color=b.Color
        GROUP BY a.Item
    )a ORDER BY Item,s')
    DROP TABLE #
    /*--结果
    Item       col0         col1         col2
    ------------- ------------------- ----------------- ---------------
    Chair      Red         White       Yellow
    Chair      90          55          232
    Table      Blue        Green       Red
    Table      124         230         159
    --*/
  • 相关阅读:
    桂电在线-转变成bootstrap版
    PHP开发APP接口---返回数据的封装类
    angularjs入门整理
    桂电在线_微信公众平台开发之-运用angularjs显示学校公告新闻列表和详情页面
    AngularJS学习-初识
    Nonsense Alphabet
    Even and Odd Functions
    研究生应该怎么学习?
    王菲观点
    Paul and Joyce are going to a movie(More listening of Unit 2)
  • 原文地址:https://www.cnblogs.com/shihao/p/2531876.html
Copyright © 2020-2023  润新知