Skip to content
Advertisement

How do I return values from multiple columns when the column names are based on a variable result [closed]

I have a table in SQL Server which lists dates for different stages in a journey in separate columns. I also have a column which shows the current stage of the journey.

For each stage, there is a column header denoting the stage name, and in the column will be the date associated to that stage.

I want to run a SELECT statement that will match the ‘current stage’ to a column name and return the date associated.

For example this could be the table (the actual table has 40 stages – don’t ask!):

I would like to write a SELECT statement that would show:

Advertisement

Answer

The following query using a dynamic UNPIVOT operation will do the work:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement