【问题标题】:Converting rows into columns and vice versa for part of table in oracle 10g在 oracle 10g 中将行转换为列,反之亦然
【发布时间】:2017-10-24 06:20:08
【问题描述】:

我有一个表格输出如下:

class | student | week | eng |  maths | science
  1   |   stu1  |   1  | 67  |   78   |     89
  1   |   stu2  |   1  | 78  |   88   |     90
  1   |   stu3  |   1  | 45  |   34   |     45
  1   |   stu1  |   2  | 67  |   45   |     34

我需要最终输出为:

class | student |   sub   |  week1 |    week2
  1   |   stu1  |   eng   |     67 |    67
  1   |   stu1  |   maths |     78 |    45
  1   |   stu1  | science |     89 |    34
  1   |   stu2  |   eng   |     78 |    89
  1   |   stu2  |   maths |     88 |    90
  1   |   stu2  | science |     90 |    89
  1   |   stu3  |   eng   |     45 |    
  1   |   stu3  |   maths |     34 |    
  1   |   stu3  | science |     45 | 

即在表格中,仅对一部分,行转列,列转行。

我正在使用 oracle 10g。

这是我对第一个表的查询。

select class, student,
to_char(dt,'WW') as week,
sum(case when sm.sub='eng' then 'eng' end) as eng,
sum(case when sm.sub='maths' then 'maths' end) as maths,
sum(case when sm.sub='science' then 'science' end) as science
from studentList sl left join studentMarks sm
on sl.stId=sm.stId
group by class, student, to_char(dt,'WW')
order by class, student;

【问题讨论】:

    标签: sql oracle10g pivot


    【解决方案1】:

    为此使用 PIVOT/UNPIVOT 运算符。请在这里找到一篇好文章: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-27
    • 2013-01-12
    • 2021-09-12
    • 1970-01-01
    • 2010-12-03
    • 2011-10-08
    • 2013-03-15
    • 2019-09-19
    相关资源
    最近更新 更多