2017-02-15 46 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