2017-02-15 47 views
0

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

当前结果

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

使用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) 

如果要按subcodesublevel排序,则不需要#列。

你应该通过拆分数据考虑了模型的规范化成两个表,例如:

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); 
+0

给定的帮助非常感谢。这与使用“union all”工作正常。并感谢表规范化提示以及。不幸的是,我们现在不能改变表格结构。 –

+1

是的,'union all'是有道理的,我为未来的读者添加了这个。 – klin