I have two tables as:
Table_1
Question01 Answer01 Question02 Answer02 QuestionN AnswerN
-------------------------------------------------------------------
Favourite Red Favourite Chips Favourite Black Beatles
Colour? Food? Song?
Table_2
No.
----------
Question01
Question02
...
QuestionN
And I want to get a result that looks like this:
No. | Questions
----------
Question01 Favourite Colour?
Question02 Favourite Food?
...
QuestionN Favourite Song?
I need the resulting table to be dynamic as the number of questions can vary.
Does anyone know how I would go about doing this?
You can use dynamic sql and unpivot for this:
DECLARE @sql NVARCHAR(max)
DECLARE @column_list NVARCHAR(max) = N''
SELECT @column_list += QUOTENAME(q) + ',' FROM Table_2
SET @column_list = SUBSTRING(@column_list, 1, LEN(@column_list) -1)
SET @sql = CONCAT(N'
SELECT up.[No.], up.[Questions] FROM (
SELECT
',@column_list,N'
FROM Table_1
) p
UNPIVOT ([No.] FOR [Questions] IN (',@column_list,N')) AS up')
PRINT @sql
EXEC (@sql)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.