记一次行转列-sql
Posted zuoruining
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了记一次行转列-sql相关的知识,希望对你有一定的参考价值。
创建测试表
CREATE TABLE ZLTEST ( TEACHER_NO VARCHAR(10), WEEK_NO VARCHAR(10), COURSE VARCHAR(30) )
插入数据
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
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 动态行转列(参数化表名分组列行转列字段字段值)