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)

  • 相关阅读:
    持续集成系统敏捷开发的基石
    云计算对IT产业的影响
    类封装的驱动程序
    竹林蹊径:深入浅出Windows驱动开发
    云计算的SPI服务模型
    什么是云计算
    多态
    我们需要什么样的计算
    电子工业的发展也带动了电子设计自动化技术
    云计算的部署模型
  • 原文地址:https://www.cnblogs.com/Depingblogs/p/14335470.html
Copyright © 2011-2022 走看看