记一次行转列-sql

Posted zuoruining

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了记一次行转列-sql相关的知识,希望对你有一定的参考价值。

  1. 创建测试表

    CREATE TABLE  ZLTEST (
      TEACHER_NO VARCHAR(10),
      WEEK_NO VARCHAR(10),
      COURSE VARCHAR(30)
    )
  2. 插入数据

    INSERT INTO ZLTEST VALUES (1,1,'有')
    INSERT INTO ZLTEST VALUES (2,2,'有')
    INSERT INTO ZLTEST VALUES (1,3,'有')
    INSERT INTO ZLTEST VALUES (2,4,'有')
    INSERT INTO ZLTEST VALUES (1,5,'有')
    INSERT INTO ZLTEST VALUES (2,1,'有')

    技术分享图片
    3、case when实现:

    SELECT ZLTEST.TEACHER_NO AS 老师编号,
      max(CASE WHEN WEEK_NO =1 THEN COURSE ELSE '' END ) as 星期一,
      max(CASE WHEN WEEK_NO = 2 THEN COURSE ELSE '' END ) AS 星期二,
      max(CASE WHEN WEEK_NO = 3 THEN COURSE ELSE '' END ) AS 星期三,
      max(CASE WHEN WEEK_NO = 4 THEN COURSE ELSE '' END ) AS 星期四,
      max(CASE WHEN WEEK_NO = 5 THEN COURSE ELSE ''  END ) AS 星期五
    FROM ZLTEST GROUP BY ZLTEST.TEACHER_NO

    技术分享图片

  3. ORACLE 数据库可以用decode函数实现:

    SELECT ZLTEST.TEACHER_NO AS 老师编号,
      max(decode(t.WEEK_NO,'1',COURSE)) as 星期一,
      max(decode(t.WEEK_NO,'2',COURSE)) as 星期二,
      max(decode(t.WEEK_NO,'3',COURSE)) AS 星期三,
      max(decode(t.WEEK_NO,'4',COURSE)) AS 星期四,
      max(decode(t.WEEK_NO,)'5',COURSE) AS 星期五
    FROM ZLTEST
    GROUP BY  ZLTEST.TEACHER_NO
    ORDER BY ZLTEST.TEACHER_NO

以上是关于记一次行转列-sql的主要内容,如果未能解决你的问题,请参考以下文章

sql server 2012 行转列

SQL Server 动态行转列(参数化表名分组列行转列字段字段值)

通过sql实现动态行转列

SQL Server 动态行转列(参数化表名分组列行转列字段字段值)

ORAClE sql如何实现行转列?

oracle行转列sql怎么写?