如何使用SQL将2d表转换为3d表

时间:2014-09-11 14:34:09

标签: sql oracle

如何使用SQL

将2d表转换为3d表

样本表:

实际表格

    School  class     number 
    S1      I         23
    S1      II        12
    S1      III       54
    S2      I         57
    S2      II        12
    S2      III       81
    S3      I         12
    S3      II        25
    S3      III       65

并将其转换为表格

     I       II     III
S1   23      12     54
S2   57      12     81
S3   12      25     65

1 个答案:

答案 0 :(得分:1)

正如Sean Lange所说,假设您使用的是11g或更高,请使用pivot clause

select *
from classes
pivot (max(class_size) as class_size
  for (class) in ('I' as i, 'II' as ii, 'III' as iii))
order by school;

SCHOOL I_CLASS_SIZE II_CLASS_SIZE III_CLASS_SIZE
------ ------------ ------------- --------------
S1               23            12             54 
S2               57            12             81 
S3               12            25             65 

SQL Fiddle

如果您仍然使用不支持数据透视的早期版本,那么您可以使用手动方法执行相同的操作:

select school,
  max(case when class = 'I' then class_size end) as i,
  max(case when class = 'II' then class_size end) as ii,
  max(case when class = 'III' then class_size end) as iii
from classes
group by school
order by school;

SCHOOL          I         II        III
------ ---------- ---------- ----------
S1             23         12         54 
S2             57         12         81 
S3             12         25         65 

SQL Fiddle

要显示每所学校的总数,只需添加sum

select school,
  max(case when class = 'I' then class_size end) as i,
  max(case when class = 'II' then class_size end) as ii,
  max(case when class = 'III' then class_size end) as iii,
  sum(class_size) as total
from classes
group by school
order by school;

SQL Fiddle

要对列进行求和,您可以使用rollup()

select school,
  max(case when class = 'I' then class_size end) as i,
  max(case when class = 'II' then class_size end) as ii,
  max(case when class = 'III' then class_size end) as iii,
  sum(class_size) as total
from classes
group by rollup(school)
order by school;

SCHOOL          I         II        III      TOTAL
------ ---------- ---------- ---------- ----------
S1             23         12         54         89 
S2             57         12         81        150 
S3             12         25         65        102 
               57         25         81        341 

SQL Fiddle。但是,您可能应该在客户端/应用程序中执行此操作。 SQL * Plus可以使用其compute命令自动执行此操作,例如。

相关问题