zoukankan      html  css  js  c++  java
  • sql行转列语句

    代码

    --delete from #tba
    --
    delete from #tbb

    create  table #tba ( sid int ,n varchar(20) )

    create table #tbb (sid int ,c varchar(20) ,s float )

    insert #tba
    select 1,'z1' union all
    select 2,'z2' union all
    select 3,'z3' union all
    select 4,'z4' union all
    select 5,'z5' 

    insert #tbb
    select 1'shuxue',50 union all
    select 1'english'60 union all
    select 1'yuwen'90 union all

    select 2'shuxue',70 union all
    select 2'english'40 union all
    select 2'yuwen'35 union all

    select 3'shuxue',57 union all
    select 3'english'64 union all
    select 3'yuwen'93 union all

    select 8'shuxue',55 union all
    select 8'english'84 union all
    select 8'yuwen'90 union all

    select 4'english'65 union all
    select 4'yuwen'33 
     

    --select * from @tba
    --
    select * from #tbb

    --固定字段方式行转列
    /*

    select sid,sum(case when c = 'shuxue' then s else 0 end) as 'shuxue',
    sum(case when c = 'english' then s else 0 end) as 'english',
    sum(case when c = 'yuwen' then s else 0 end) as 'yuwen'
    from @tbb 
    group by sid
    */

    --动态方式行转列
    declare @sql varchar(8000)
    set @sql = 'select sid,'
    select @sql = @sql + 'sum(case when c = '''+c+''' then s else null end) as '''+c+''','
    from (select distinct c from #tbb) as B 
    set @sql = left(@sql,len(@sql)-1+ ' from #tbb group by sid'

    --PRINT @SQL 
    exec(@sql)
    /*
    */

    --回顾下左外连接,右外连接,全外连接;交叉连接(笛卡尔乘积),内连接
    --
    select * from @tba a left join @tbb b on a.sid = b.sid 

    --select * from @tba a right join @tbb b on a.sid = b.sid

    --select * from @tba a full join @tbb b on a.sid = b.sid

    --select * from @tba cross join @tbb

    --select * from @tba a inner join @tbb b on a.sid = b.sid
    --
    select * from @tba a join @tbb b on a.sid = b.sid
    --
    select * from @tba a, @tbb b where a.sid = b.sid

    --having关键字
    /*

    select a.sid,count(a.sid) cid from @tba a left join @tbb b on a.sid = b.sid
    group by a.sid having count(a.sid) > 2

    --select count(sid) as cid from @tbb group by sid  having count(sid)>2 

    */
  • 相关阅读:
    [HAOI2015]按位或
    【bzoj 4675】 点对游戏
    [WC2013]糖果公园
    [国家集训队]数颜色 / 维护队列
    【bzoj 3252】攻略
    [ZJOI2016]小星星
    hdu-1712 ACboy needs your help---分组背包
    hdu-2844&&POJ-1742 Coins---多重背包
    UVA-147 Dollars---完全背包+打表
    hdu-2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活---多重背包
  • 原文地址:https://www.cnblogs.com/ztotem/p/1905897.html
Copyright © 2011-2022 走看看