码迷,mamicode.com
首页 > 数据库 > 详细

记一次行转列-sql

时间:2018-05-30 21:30:29      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:char   函数实现   img   The   sele   oracle   select   tps   case when   

  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

标签:char   函数实现   img   The   sele   oracle   select   tps   case when   

原文地址:https://www.cnblogs.com/zuoruining/p/9112780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!