sql动态地将列转换为行

rseugnpd  于 2021-07-27  发布在  Java
关注(0)|答案(2)|浏览(362)

在下表中,我需要将列转换为行
tbl\U调查:

SurveyID   Quest_1  Quest_2  Quest_3
             7        1         1        1
             8        2         2        2
             9        3         3        3

我需要得到以下结果:

SurveyID  Questions  Rating 
              7    Quest_1      1
              7    Quest_2      1
              7    Quest_3      1
              8    Quest_1      2
              8    Quest_2      2
              8    Quest_3      2
              9    Quest_1      3
              9    Quest_2      3
              9    Quest_3      3

为了得到这个结果,我使用了以下代码:

SELECT [SurveyID], [Question], [Rating]
       FROM [dbo].[tbl_Survey]

       UNPIVOT
        (
         [Rating]
          FOR [Question] in ([Quest_1], [Quest_2], [Quest_3])
        ) AS SurveyUnpivot

但是,我的任务1,任务2,任务3的值可能会被更改/甚至添加一个新的一次。。。
有没有办法对它们进行编码,这样就可以用于任何文本值(不仅仅是quest{1 2 3)?不需要用unpivot。。。可能还有别的办法
谢谢您

fnatzsnv

fnatzsnv1#

你需要做一个动态的 UNPIVOT . 检查以下示例:

DROP TABLE IF EXISTS [dbo].[DataSource];

CREATE TABLE [dbo].[DataSource]
(
    [SurveyID] INT
   ,[Quest_1] INT
   ,[Quest_2] INT
   ,[Quest_3] INT
);

INSERT INTO [dbo].[DataSource] ([SurveyID], [Quest_1], [Quest_2], [Quest_3])
VALUES (7, 1, 1, 1)
      ,(8, 2, 2, 2)
      ,(9, 3, 3, 3);

GO

DECLARE @DynamicTSQLStatement NVARCHAR(MAX);
DECLARE @DynamicTSQLUnpivotColumns NVARCHAR(MAX);

SET @DynamicTSQLUnpivotColumns = STUFF
(
    (
        SELECT ',' + QUOTENAME([name])
        FROM [sys].[columns]
        WHERE [object_id] = OBJECT_ID('[dbo].[DataSource]')
            AND [name] <> 'SurveyID'
        ORDER BY [name]
        FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(MAX)')
    ,1
    ,1
    ,''
);

SET @DynamicTSQLStatement = N'
SELECT [SurveyID], [Question], [Rating]
FROM [dbo].[DataSource]
UNPIVOT
(
    [Rating] FOR [Question] in (' + @DynamicTSQLUnpivotColumns + ')
) AS SurveyUnpivot';

EXEC sp_executesql @DynamicTSQLStatement;
jobtbby3

jobtbby32#

我更喜欢在这里使用联合,因为使用联合所需的语法非常冗长 PIVOT 以及 UNPIVOT :

SELECT SurveyID, 'Quest_1' AS Questions, Quest_1 AS Rating FROM tbl_Survey UNION ALL
SELECT SurveyID, 'Quest_2', Quest_2 FROM tbl_Survey UNION ALL
SELECT SurveyID, 'Quest_3', Quest_3 FROM tbl_Survey
ORDER BY SurveyID, Rating;

相关问题