zoukankan      html  css  js  c++  java
  • SQL 行转列的两种做法

    if object_id('tb')is not null drop table tb
    Go
    create table tb(姓名 varchar(10),课程 varchar(10),分数 int)
    insert into tb values('张三','语文',74)
    insert into tb values('张三','数学',83)
    insert into tb values('张三','物理',93)
    insert into tb values('李四','语文',74)
    insert into tb values('李四','数学',84)
    insert into tb values('李四','物理',94)
    go
    select * from tb

    -- 使用case when (SQL2000以上)
    select 姓名,
    max(case 课程 when '语文' then 分数 else 0 end)语文,
    max(case 课程 when '数学'then 分数 else 0 end)数学,
    max(case 课程 when '物理'then 分数 else 0 end)物理
    from tb
    group by 姓名

    -- 使用pivot
    select * from tb pivot(max(分数) for 课程 in (语文,数学,物理))a

    -- 另外也可以通过写存储过程实现,但比较麻烦。

  • 相关阅读:
    Linux踩坑填坑记录
    Scala安装后,在IDEA中配置
    Centos 搭建Hadoop
    conductor FAQ
    conductor Workflow Metrics
    conductor APIs
    Extending Conductor
    conductor任务域
    Conductor Task Workers
    Conductor Server
  • 原文地址:https://www.cnblogs.com/chengeng/p/5975925.html
Copyright © 2011-2022 走看看