Home > Mobile >  Join two or more columns using UNPIVOT - SQL Server 2017
Join two or more columns using UNPIVOT - SQL Server 2017

Time:02-22

Could you please help me, I'm trying to move the columns to rows using UNPIVOT, but I need it, it doesn't work well for me. I need also the column name to be displayed in the row not just the value.

WITH ENCUESTA1

    AS  (
            SELECT
             Cod as 'Codigo' 
            ,Wifi as 'Wifi'
            ,EntreTvCable as 'Cable'

            FROM epha_rooms
        )
        

SELECT Codigo, Pregunta 
FROM ENCUESTA1
UNPIVOT
(
    Pregunta for col in ([Wifi], [Cable])
)un;

Result:

Codigo  Pregunta
---------------------
20      10
20      -7
21      10
21      4
22      10
22      10
23      10

I need to get this result:

Codigo  Pregunta    Value
-------------------------------
20      Wifi        10
20      Cable       -7
21      Wifi        10
21      Cable       4
22      Wifi        10
22      Cable       10
23      Wifi        10

CodePudding user response:

SQL Server is not installed on my computer, but based this documentation, I hope this code below helps you.

WITH ENCUESTA1

AS  (
        SELECT
         Cod as 'Codigo' 
        ,Wifi as 'Wifi'
        ,EntreTvCable as 'Cable'

        FROM epha_rooms
    )
    

SELECT Codigo, Pregunta, Value
FROM ENCUESTA1
UNPIVOT
(
    Value for Pregunta in ([Wifi], [Cable])
) un;
  • Related