• 使用动态SQL语句实现简单的行列转置(动态产生列)


    原始数据如下图所示:(商品的销售明细)
    date=业务日期;Item=商品名称;saleqty=销售数量;

    -- 建立测试数据(表)
    create table test (Date varchar(10), item char(10),saleqty int)
    insert test values('2010-01-01','AAA',8)
    insert test values('2010-01-02','AAA',4)
    insert test values('2010-01-03','AAA',5)
    insert test values('2010-01-01','BBB',1)
    insert test values('2010-01-02','CCC',2)
    insert test values('2010-01-03','DDD',6)

    需要实现的报表样式:每一行既每一天,显示所有商品(列)该天的销售数量;

    实现的方法和思路如下:

    -- 实现结果的静态SQL语句写法
    -- 整理报表需要的格式
    select date,
    case item when 'AAA' then saleqty when null then 0 end as AAA,
    case item when 'BBB' then saleqty when null then 0 end as BBB,
    case item when 'CCC' then saleqty when null then 0 end as CCC,
    case item when 'DDD' then saleqty when null then 0 end as DDD
    from test

     

      

    -- 按日期汇总行
    select date,
    sum(case item when 'AAA' then saleqty when null then 0 end) as AAA,
    sum(case item when 'BBB' then saleqty when null then 0 end) as BBB,
    sum(case item when 'CCC' then saleqty when null then 0 end) as CCC,
    sum(case item when 'DDD' then saleqty when null then 0 end) as DDD
    from test 
    group by date

     

    -- 处理数据:将空值的栏位填入数字0;
    select date,
    isnull (sum(case item when 'AAA' then saleqty end),0) as AAA,
    isnull (sum(case item when 'BBB' then saleqty end),0) as BBB,
    isnull (sum(case item when 'CCC' then saleqty end),0) as CCC,
    isnull (sum(case item when 'DDD' then saleqty end),0) as DDD
    from test 
    group by date

    静态SQL语句编写完成!

    -- 需要动态实现的SQL部分
    isnull (sum(case item when 'AAA' then saleqty end),0) as AAA,
    isnull (sum(case item when 'BBB' then saleqty end),0) as BBB,
    isnull (sum(case item when 'CCC' then saleqty end),0) as CCC,
    isnull (sum(case item when 'DDD' then saleqty end),0) as DDD

    -- 动态语句的实现
    select 'isnull (sum(case item when '''+item+''' then saleqty end),0) as ['+item+']' 
    from (select distinct item from test) as a
    -- 这一步很关键:利用结果集给变量赋值;

    -- 完成!
    declare @sql varchar(8000)
    set @sql = 'select Date'
    select @sql = @sql + ',isnull (sum(case item when '''+item+''' then saleqty end),0) as ['+item+']' 
    from (select distinct item from test) as a
    select @sql = @sql+' from test group by date'
    exec(@sql)

    -- 删除测试数据(表)
    drop table test

  • 相关阅读:
    微信小程序swiper个性化定制
    php脚本巧用正则批量替换函数参数
    Phpstorm中添加xdebug调试工具。
    apache服务器禁止浏览目录文件
    mysql_connect()函数使用报错
    composer创建新项目报错
    安利一个简单的零配置的命令行http服务器(http-server)
    Laravel笔记之tinker和时间函数
    即时通信2
    即时通信1
  • 原文地址:https://www.cnblogs.com/ShaYeBlog/p/3594517.html
Copyright © 2020-2023  润新知