zoukankan      html  css  js  c++  java
  • 动态行转列且一行转多列

    if object_id('tempdb..#test') is not null
    drop table #test
    create table #test
    ( name nvarchar(200),
    orderdate varchar(7),
    ordernum int ,
    comnum int
    )

    insert into #test
    select 'AAA','2019-01',77,77
    union all
    select 'AAA','2019-02',66,77
    union all
    select 'BBB','2019-03',96,86
    union all
    select 'AAA','2019-04',88,89
    union all
    select 'BBB','2019-04',120,115
    select *from #test
    declare @event varchar(3000)='',@sql varchar(3000)='',@queryexp varchar(3000)=''
    if object_id('tempdb..#hbTab') is not null
    drop table #hbtab
    select name,(orderdate+'_shouli') as [year],ordernum,orderdate into #hbtab from #test
    select * from #hbtab
    --列转行
    insert into #hbtab
    select name,(orderdate+'_banjie') as [year],comnum,orderdate from #test
    select * from #hbtab
    --获取行的属性
    --select *from #hbtab
    select @event=@event+',['+[year]+']' from (select distinct [year] from #hbtab) a order by [year]
    print @event
    select @queryexp=@queryexp+',max(['+[year]+']) as '+'['+[year]+']' from (select distinct [year] from #hbtab) a order by [year]
    print @queryexp
    select @queryexp=right(@queryexp,len(@queryexp)-1)
    print @queryexp
    select @event=right(@event,len(@event)-1)
    print @event

    --select *from #hbtab order by year
    set @sql='select name,'+@queryexp+' from( select name,'+@event +'from #hbtab a
    pivot (max(ordernum) for year in('+@event+')
    ) as pv ) b group by name'
    print @sql
    exec(@sql)

  • 相关阅读:
    nproc 查看系统可用处理单元数
    c++内存泄露的坑
    内存泄露脚本
    c++内存问题(转)
    tmp
    kprobe
    内存对齐算法
    正则
    P3261 [JLOI2015]城池攻占有趣的做法
    CF1620C BAString题解
  • 原文地址:https://www.cnblogs.com/Depingblogs/p/14335470.html
Copyright © 2011-2022 走看看