I have a table that has an unknown number of tasks like so:
+----------+--------+--------+--------+--------+--------+
| CourseID | Task 1 | Task 2 | Task 3 | Task 4 | Task 5 |
+----------+--------+--------+--------+--------+--------+
| EN01 | 15 | 20 | 15 | 25 | 30 |
+----------+--------+--------+--------+--------+--------+
Sometimes there are 5 tasks, sometimes there are more. How do I write a dynamic transpose query using pivot to get this result without having to speficy the column headers specifically other than column header is like 'Task%'
+----------+-------------+------------+
| CourseID | Task Number | Task Total |
+----------+-------------+------------+
| EN01 | Task 1 | 15 |
| EN01 | Task 2 | 20 |
| EN01 | Task 3 | 15 |
| EN01 | Task 4 | 25 |
| EN01 | Task 5 | 30 |
+----------+-------------+------------+
EDIT: Basically I need the reverse of this: Efficiently convert rows to columns in sql server
I can do it manually:
-- Unpivot the table.
SELECT [Class], TaskNumber, TaskTotal
FROM
(SELECT [Class], [Task 1], [Task 2], [Task 3], [Task 4]
FROM [Modules].[dbo].[2018-12ah] where [Given] like '%J:%') p
UNPIVOT
(TaskTotal FOR TaskNumber IN
([Task 1], [Task 2], [Task 3], [Task 4])
)AS Unpivot;
GO
Next step that i'm not sure how to do is dynamically building in tasks 1 to Z so I don't have to specify them in the query.
Thank you