有没有一种有效的方法可以将行转换为SQL中的列?

时间:2020-09-16 14:24:10

标签: sql sql-server

我有一些看起来像这样的数据:

Ordinal    Question   Answer
-------    --------   ----
1          One        Alpha
2          Two        Beta
3          Three      Gamma

我想将其转换为此:

Question1 Answer1    Question2 Answer2   Question3 Answer3
--        --         --        --        --        --
One       Alpha      Two       Beta      Three     Gamma

我使用while循环来工作,但是我怀疑它真的很慢。存储过程中的某些东西至少很慢!有没有更有效的方法可以做到这一点?枢轴,也许?我可以理解在Excel中进行数据透视,但是我从未在SQL中理解它...

这是我现在拥有的while循环,列列表被截断了:

while (@CurrentID <= @MaxID)
    begin

        -- reset the ordinal and counter
        declare @CurrentOrdinal int = null;
        declare @MaxOrdinal int = null;
        select @CurrentOrdinal = min(Ordinal), @MaxOrdinal = max(Ordinal) from @Temp;
        declare @Count int = 1;

        while (@CurrentOrdinal <= @MaxOrdinal)
        begin
    
            update b
            set
                --questions
                b.Question1 = case when @Count = 1 then a.QuestionText else b.Question1 end,
                -- repeat ad infinitum, we have 125 questions and then 125 answers so it gets crazy!
            from @temp a
        inner join @Results b
            on a.AssessmentID = b.AssessmentID
        where
            a.Ordinal = @CurrentOrdinal;

        -- get next ordinal
        select
            @CurrentOrdinal = min(a.Ordinal)
        from @temp a
        where
            a.Ordinal > @CurrentOrdinal;

        -- increment the counter
        set @Count = @Count + 1;

    end

    select @CurrentID = min(a.AssessmentID) 
    from @temp a
    where
        a.AssessmentID > @CurrentID;
end

1 个答案:

答案 0 :(得分:1)

WITH
indata         ( ordinal,   question , answer ) AS (
          SELECT 1      ,  'One'     ,'Alpha'
UNION ALL SELECT 2      ,  'Two'     ,'Beta'
UNION ALL SELECT 3      ,  'Three'   ,'Gamma'
)
SELECT
  MAX(CASE ordinal WHEN 1 THEN question END) AS question1
, MAX(CASE ordinal WHEN 1 THEN answer   END) AS answer1
, MAX(CASE ordinal WHEN 2 THEN question END) AS question2
, MAX(CASE ordinal WHEN 2 THEN answer   END) AS answer2
, MAX(CASE ordinal WHEN 3 THEN question END) AS question3
, MAX(CASE ordinal WHEN 3 THEN answer   END) AS answer3
FROM indata;
-- out  question1 | answer1 | question2 | answer2 | question3 | answer3 
-- out -----------+---------+-----------+---------+-----------+---------
-- out  One       | Alpha   | Two       | Beta    | Three     | Gamma