zoukankan      html  css  js  c++  java
  • sql 动态行转列

    create table u01
    (医案编号 varchar(5),药物编号 varchar(5))
     
    insert into u01
     select '01','01' union all
     select '01','02' union all
     select '01','03' union all
     select '02','07' union all
     select '02','08' union all
     select '03','06' union all
     select '04','01' union all
     select '04','02' union all
     select '04','03' union all
     select '04','04' union all
     select '04','05' union all
     select '05','09' union all
     select '05','08'
     
     
    declare @tsql varchar(6000),@c1 varchar(1000),@c2 varchar(1000)
     
    select @c1=isnull(@c1+',','')+'isnull(['+rtrim(number)+'],'''') ''药物'+rtrim(number)+''' ',
           @c2=isnull(@c2+',','')+'['+rtrim(number)+']'
     from master.dbo.spt_values
     where type='P' and number>=1 and number<=
     (select max(c) from (select count(1) 'c' from u01 group by 医案编号) t)
      
    select @tsql='select 医案编号,'+@c1+'
    from (select 医案编号,药物编号,
                 row_number() over(partition by 医案编号 order by getdate()) ''rn''
          from u01) t
    pivot(max(药物编号) for rn in ('+@c2+')) p '
     
    exec(@tsql)
     
    /*
    医案编号  药物1  药物2  药物3  药物4  药物5
    ----- ----- ----- ----- ----- -----
     01     01     02     03          
     02     07     08                
     03     06                      
     04     01     02     03     04     05
     05     09     08                
     
    (5 row(s) affected)
    */
    

      来源:http://bbs.csdn.net/

  • 相关阅读:
    图论-最短路
    windows对拍及其应用
    RMQ与st表
    树状数组
    二分和三分题
    [转载]图论500题
    浏览器请求背后的网络数据传输过程
    百度ocr文字识别接口使用
    Mysql启动报错解决方案:Failed to open log (file './mysql-bin.000901', errno 2)
    Mac环境下nginx https配置
  • 原文地址:https://www.cnblogs.com/lb12081116/p/4517266.html
Copyright © 2011-2022 走看看