调查数据的数据转换-SQL Server

时间:2018-11-15 19:55:40

标签: sql sql-server pivot-table

我是新来的,还在学习,所以请在尝试解释自己要做的事情时给我恩典。

我有类似这样的数据

what I currently have

但是,我希望它看起来像这样

What I want

我已将数据加载到我们的SQL Server中,并且需要知道如何使用SQL代码对其进行转换。

有人可以帮我吗?

3 个答案:

答案 0 :(得分:1)

我会使用cross apply

select t.sr_no, v.*
from t cross apply
     (values ('I like to go to school', [I like to go to school]),
             ('Learning is fun', [Learning is fun])
     ) v(question, answer);

答案 1 :(得分:1)

您需要使用“ unpivot”关键字,例如:

select u.SrNo, u.question, u.Answer
from yourtable
unpivot
(
  Answer
  for question in ([I like to go to school], [Learning is fun])
) u;

答案 2 :(得分:1)

这是戈登上面提议的动态版本...

IF OBJECT_ID('CodeTest.dbo.TestData', 'U') IS NOT NULL 
BEGIN DROP TABLE dbo.TestData; END;

CREATE TABLE dbo.TestData (
    SrNum INT NOT NULL,
    [I like to go to school] CHAR(3) NOT NULL,
    [Learning is fun] CHAR(3) NOT NULL 
    );
INSERT dbo.TestData (SrNum, [I like to go to school], [Learning is fun]) VALUES
    (1, 'Yes', 'Yes'), (2, 'Yes', 'Yes');


--=================================================

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT 
    @sql = CONCAT(@sql, N',
        (', c.column_id, N', ''', c.name, N''', td.[', c.name, N'])')
FROM
    sys.columns c
WHERE 
    c.object_id = OBJECT_ID('CodeTest.dbo.TestData', 'U')
    AND c.column_id > 1

SET @sql = CONCAT(N'
SELECT 
    td.SrNum,
    qa.Question,
    qa.Answer
FROM 
    dbo.TestData td
    CROSS APPLY ( VALUES', 
    STUFF(@sql, 1, 1, N''), N'
        ) qa (Qnum, Question, Answer)
ORDER BY 
    td.SrNum,
    qa.Qnum;');

EXEC sys.sp_executesql @sql;

结果:

SrNum       Question               Answer
----------- ---------------------- ------
1           I like to go to school Yes
1           Learning is fun        Yes
2           I like to go to school Yes
2           Learning is fun        Yes