from this
| STU | SUB |
| 1 | MAT |
| 1 | CHEM |
| 1 | PHY |
to this
| STU | SUB1 | SUB2 | SUB3 |
| 1 | MAT | CHEM | PHY |
data of 1 student is in 3 rows i want in 1 row in sql
from this
| STU | SUB |
| 1 | MAT |
| 1 | CHEM |
| 1 | PHY |
to this
| STU | SUB1 | SUB2 | SUB3 |
| 1 | MAT | CHEM | PHY |
data of 1 student is in 3 rows i want in 1 row in sql
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Amit MohantyRank #112 · 20K reputationPosted Jan 22, 2025, 3:37 AM EST
Try this:
SELECT STU, [MAT] AS SUB1, [CHEM] AS SUB2, [PHY] AS SUB3 FROM (SELECT STU, SUB FROM your_table_name) AS SourceTable PIVOT (MAX(SUB) FOR SUB IN ([MAT], [CHEM], [PHY])) AS PivotTable;Jignesh KumarRank #91 · 22.9K reputationPosted Jan 22, 2025, 3:59 AM EST
Hello jihok,
Please use this query and you can convert your result,
WITH RankedSubjects AS ( SELECT STU, SUB, ROW_NUMBER() OVER (PARTITION BY STU ORDER BY SUB) AS RowNum FROM YourTable ) SELECT STU, [1] AS SUB1, [2] AS SUB2, [3] AS SUB3 FROM RankedSubjects PIVOT ( MAX(SUB) FOR RowNum IN ([1], [2], [3]) ) AS PivotTable;