• SQL 行列转换 PIVOT


    ALTER proc [dbo].[PIVOT_Test] 
    @year1 varchar(4),
    @year2 varchar(4),
    @year3 varchar(4),
    @quarter varchar(2)
    as
    select column1,sum(column2) column2,year,month into #t1 from table1
    where year in(@year1,@year2,@year3) 
    and 1=case when isnull(@quarter,0)=0 then 1 
               when @quarter=1 and month in(1,2,3) then 1
               when @quarter=2 and month in(4,5,6) then 1
               when @quarter=3 and month in(7,8,9) then 1 
               when @quarter=4 and month in (10,11,12) then 1 end
    group by column1,year,month
    
    select column2 ,a.year,b.productcode,b.ProductValueCN into #t2 from #t1 a
    left join table2 b on a.packagecode=b.packagecode
    left join table3 c on a.packagecode=c.packagecode and c.Year=a.Year and c.Month=a.Month
    where ProductCode is not null
    group by a.year,b.productcode,b.ProductValueCN
    --动态列转行
    declare @sql varchar(max)
    set @sql='select ProductCode+''(''+ProductValueCN+'')'' as ProductValueCN,isnull(['+@year1+']/1000,0) as year1,isnull(['+@year2+']/1000,0) as year2,isnull(['+@year3+']/1000,0) as year3 from #t2 
    as p  PIVOT ( SUM(salescount) FOR year IN ('+'['+@year1+'],['+@year2+'],['+@year3+']'+') ) AS T order by ProductValueCN'
    print @sql
    exec (@sql)
    
    drop table #t2
    drop table #t1
  • 相关阅读:
    爬虫之爬取淘宝主题市场主要产品信息
    Linux内核11-定时器和时间管理
    UNIX8-进程控制
    UNIX7-进程环境
    Unix3-文件I/O接口
    Linux进程-打开的文件
    递归与二叉树_leetcode230
    递归与二叉树_leetcode235
    递归与二叉树_leetcode226
    递归与二叉树_leetcode222
  • 原文地址:https://www.cnblogs.com/daniel-niu/p/10688574.html
Copyright © 2020-2023  润新知