我要绕一列,它返回两行而不是一行,请帮忙。
我的桌子:
Key Name column_title column_answer Date
--------------------------------------------------
101 Stacy column1 answer1 08/9/2019
101 Stacy column2 answer2 08/9/2019
查询:
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', ' + QUOTENAME(column_title)
FROM (SELECT column_title from ##Questions) AS x;
SELECT @columns;
SELECT STUFF(@columns, 1, 2, '');
SELECT STUFF(REPLACE(@columns, ', [', ',['), 1, 1, '');
SET @sql =
N'SELECT
key, name, ' + STUFF(@columns, 1, 2, '') + '
INTO ####TempTable
FROM
(SELECT * FROM Mytable) AS j
PIVOT
(MAX(column_answer)
FOR column_title IN (' + STUFF(REPLACE(@columns, ', [', ',['), 1, 1, '') + ')) AS p ';
EXEC sp_executesql @sql;
此语句返回两行:
Key Name Column1 column2 Date
-------------------------------------------
101 Stacy answer1 null 08/9/2019
101 Stacy null answer2 08/9/2019
我想得到:
Key Name Column1 column2 Date
-------------------------------------------
101 Stacy answer1 answer2 08/9/2019