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

利用組合:

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

感謝を。これは "union all"を使ってうまくいきます。テーブルの正規化のヒントもありがとう。残念ながら、今はテーブル構造を変更することはできません。 –

+1

はい、 'union all'は意味があります、これを将来の読者に追加しました。 – klin

関連する問題