3 Réponses :
Vous pouvez utiliser le pivot comme suit:
Select * from your_table Pivot (max(marks) as marks For subject in ('maths', 'physics', 'chemistry'))
Vous pouvez utiliser une requête avec une opération PIVOT
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
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));
Vous pouvez utiliser l'agrégation conditionnelle:
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;
Vous alignez les valeurs dans chaque sujet, donc je ne vois pas pourquoi vous avez besoin du nom du sujet. Mais vous pouvez également l'inclure facilement:
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;
Utilisez-vous MySQL ou Oracle?
Pourquoi? La façon dont les données sont maintenant affichées est la façon dont elles doivent être modélisées dans une base de données relationnelle. Pour votre nouveau format, saurez-vous même à l'avance le nombre total de "sujets"? S'agit-il toujours de trois matières, pour chaque identifiant (étudiant)? Sinon, la sortie n'a même pas de sens en tant que table.