oracle横纵表相互转换

/*纵表转横表*/   

 
  1. CREATE GLOBAL TEMPORARY TABLE test2

  2. (

  3. uname VARCHAR2(10),

  4. subject VARCHAR2(10),

  5. score NUMBER

  6. );

  7.  
  8.  
  9. INSERT INTO test2 VALUES('王五','语文',80);

  10. INSERT INTO test2 VALUES('李四','语文',90);

  11. INSERT INTO test2 VALUES('李四','数学',80);

  12. INSERT INTO test2 VALUES('李四','英语',70);

  13. INSERT INTO test2 VALUES('张三','语文',80);

  14. INSERT INTO test2 VALUES('张三','数学',80);

  15. INSERT INTO test2 VALUES('张三','英语',90);

SELECT * FROM test2;

 
  1. SELECT

  2. t.uname AS 姓名,

  3. SUM(CASE t.subject WHEN '语文' THEN t.score END)AS 语文,

  4. SUM(CASE t.subject WHEN '数学' THEN t.score END)AS 数学,

  5. SUM(CASE t.subject WHEN '英语' THEN t.score END)AS 英语

  6. FROM test2 t

  7. GROUP BY t.uname;

/*横表转纵表 */ 

 
  1. CREATE GLOBAL TEMPORARY TABLE test4

  2. (

  3. uname VARCHAR2(10),

  4. chinese NUMBER,

  5. math NUMBER,

  6. english NUMBER

  7. );

  8.  
  9. INSERT INTO test4 VALUES('张三',80,90,70);

  10. INSERT INTO test4 VALUES('李四',90,85,95);

  11. INSERT INTO test4 VALUES('王五',88,75,90);

SELECT * FROM test4;


 

 
  1. SELECT * FROM (

  2. SELECT t.uname,'chinese' AS subject,t.chinese AS score FROM test4 t

  3. UNION ALL

  4. SELECT t.uname,'math' AS subject,t.math AS score FROM test4 t

  5. UNION ALL

  6. SELECT t.uname,'english' AS subject,t.english AS score FROM test4 t

  7. UNION ALL

  8. SELECT t.uname,'平均分' AS subject,CAST((t.chinese+t.math+t.english)*1.0/3 AS DECIMAL(18,2)) AS score FROM test4 t

  9. UNION ALL

  10. SELECT t.uname,'总分' AS subject,(t.chinese+t.math+t.english) AS score FROM test4 t

  11. )tb

  12. ORDER BY uname,

  13. case tb.subject

  14. when 'chinese' then 1

  15. when 'math' then 2

  16. when 'english' then 3

  17. when '平均分' then 4

  18. when '总分' then 5

  19. END

添加上计算总分和平均分

SQL语句最后加上case相当于排序。

猜你喜欢

转载自blog.csdn.net/suchahaerkang/article/details/81974223