zoukankan      html  css  js  c++  java
  • 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】ubuntu修改系统时间
    【常用脚本记录3 -- 磁盘读写脚本】
    【常用脚本记录2---压力测试脚本】
    Shell脚本相关
    cifs
    【cli命令集】
    【wlan】iw命令集合
    【实用linux命令记录】
    iOS----------关于Cornerstone的偏好设置
  • 原文地址:https://www.cnblogs.com/daniel-niu/p/10688574.html
Copyright © 2011-2022 走看看