如何将多行合并为表中的单行
Posted
技术标签:
【中文标题】如何将多行合并为表中的单行【英文标题】:How can i Merge multiple rows into single row in a table 【发布时间】:2020-11-13 14:43:36 【问题描述】:我有一个类似的数据库
我需要把这个表格转换成这种格式
【问题讨论】:
您使用的是 mysql 还是 Oracle? 为什么?现在显示数据的方式是它应该在关系数据库中的建模方式。对于您的新格式,您是否会事先知道“主题”的总数?每个(学生)身份证总是三个科目吗?如果不是,则输出甚至作为表格都没有意义。 【参考方案1】:您可以按如下方式使用枢轴:
Select * from your_table
Pivot (max(marks) as marks
For subject in ('maths', 'physics', 'chemistry'))
【讨论】:
【参考方案2】:您可以使用带有PIVOT
操作的查询
查询
WITH
marks_data (id, subject, marks)
AS
(SELECT 1, 'maths', 100 FROM DUAL
UNION ALL
SELECT 1, 'physics', 95 FROM DUAL
UNION ALL
SELECT 1, 'chemistry', 99 FROM DUAL
UNION ALL
SELECT 2, 'maths', 90 FROM DUAL
UNION ALL
SELECT 2, 'physics', 89 FROM DUAL
UNION ALL
SELECT 2, 'chemistry', 96 FROM DUAL)
SELECT *
FROM (SELECT * FROM marks_data)
PIVOT (MAX (subject) AS subject, MAX (marks) AS marks
FOR subject
IN ('maths' AS maths, 'physics' AS physics, 'chemistry' AS chemistry));
结果
ID MATHS_SUBJECT MATHS_MARKS PHYSICS_SUBJECT PHYSICS_MARKS CHEMISTRY_SUBJECT CHEMISTRY_MARKS
_____ ________________ ______________ __________________ ________________ ____________________ __________________
1 maths 100 physics 95 chemistry 99
2 maths 90 physics 89 chemistry 96
【讨论】:
【参考方案3】:您可以使用条件聚合:
select id,
max(case when subject = 'maths' then marks end) as maths_marks,
max(case when subject = 'physics' then marks end) as physics_marks,
max(case when subject = 'chemistry' then marks end) as chemistry_marks
from t
group by id;
您正在调整每个主题中的值,所以我不明白您为什么需要主题名称。但是您也可以轻松地添加它:
select id,
'maths' as subject_1,
max(case when subject = 'maths' then marks end) as marks_1,
'physics' as subject_2,
max(case when subject = 'physics' then marks end) as marks_2,
'chemistry' as subject_3,
max(case when subject = 'chemistry' then marks end) as marks_3
from t
group by id;
【讨论】:
以上是关于如何将多行合并为表中的单行的主要内容,如果未能解决你的问题,请参考以下文章