Postgresql将单行拆分为多行
我是postgresql的新手。下面是一个查询的结果,现在我需要拆分一行以获得多行。 我已经浏览了下面的链接,但仍然无法管理它。请帮忙。 当前结果Postgresql将单行拆分为多行,postgresql,Postgresql,我是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,E
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
我们想要什么
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
使用联合体:
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)
如果要按子代码
或子级别
对结果进行排序,则不需要使用#
列
你应该考虑模型的规范化,把数据分成两个表,例如:
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);
使用联合体:
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)
如果要按子代码
或子级别
对结果进行排序,则不需要使用#
列
你应该考虑模型的规范化,把数据分成两个表,例如:
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);
非常感谢你的帮助。使用“UNIONALL”可以很好地工作。同时也感谢您提供的餐桌规范化提示。不幸的是,我们现在无法更改表结构。是的,
union all
是有意义的,我为将来的读者添加了这个。非常感谢您提供的帮助。使用“UNIONALL”可以很好地工作。同时也感谢您提供的餐桌规范化提示。不幸的是,我们现在无法更改表结构。是的,union-all
是有意义的,我为将来的读者添加了这个。