Postgresql将单行拆分为多行

时间:2017-02-15 11:46:14

标签: postgresql

我是postgresql的新手。我收到了查询结果,现在我需要拆分单行来获取多行。 我已经通过以下链接,但仍然无法管理它。请帮忙。 unpivot and PostgreSQL How to split a row into multiple rows with a single query?

当前结果

id,name,sub1code,sub1level,sub1hrs,sub2code,sub2level,sub2hrs,sub3code,sub3level,sub3hrs --continue till sub15

1,Silva,CHIN,L1,12,MATH,L2,20,AGRW,L2,35

2,Perera,MATH,L3,30,ENGL,L1,10,CHIN,L2,50

我们想要什么

id,name,subcode,sublevel,subhrs

1,Silva,CHIN,L1,12

1,Silva,MATH,L2,20

1,Silva,AGRW,L2,35

2,Perera,MATH,L3,30

2,Perera,ENGL,L1,10

2,Perera,CHIN,L2,50

1 个答案:

答案 0 :(得分:1)

使用union:

select id, 1 as "#", name, sub1code, sub1level, sub1hrs
from a_table
union all
select id, 2 as "#", name, sub2code, sub2level, sub2hrs
from a_table
union all
select id, 3 as "#", name, sub3code, sub3level, sub3hrs
from a_table
order by 1, 2;

 id | # |  name  | sub1code | sub1level | sub1hrs 
----+---+--------+----------+-----------+---------
  1 | 1 | Silva  | CHIN     | L1        |      12
  1 | 2 | Silva  | MATH     | L2        |      20
  1 | 3 | Silva  | AGRW     | L2        |      35
  2 | 1 | Perera | MATH     | L3        |      30
  2 | 2 | Perera | ENGL     | L1        |      10
  2 | 3 | Perera | CHIN     | L2        |      50
(6 rows)

如果您希望按#subcode排序结果,则无需sublevel列。

您应该通过将数据拆分为两个表来考虑模型的规范化,例如:

create table students (
    id int primary key, 
    name text);

create table hours (
    id int primary key, 
    student_id int references students(id),
    code text, 
    level text, 
    hrs int);