0

I need help to find whether the below is achievable

I got a table for example

enter image description here

Is it possible to use the PIVOT sql command to convert it something like this If so could someone help me with it.

enter image description here

SqlZim
  • 37,248
  • 6
  • 41
  • 59
AK SQL
  • 57
  • 6

3 Answers3

2

without the UNPIVOT keyword you would have to do this transform by hand.

SELECT *
FROM (
    SELECT 
        [D].[UID]
        ,'Q1' AS [Question]
        ,[D].[Q1_Score] AS [Score]
        ,[D].[Category]
    FROM [DataSet] AS [D]
    UNION ALL
    SELECT 
        [D].[UID]
        ,'Q2' AS [Question]
        ,[D].[Q2_Score] AS [Score]
        ,[D].[Category]
    FROM [DataSet] AS [D]
    UNION ALL
    SELECT 
        [D].[UID]
        ,'Q3' AS [Question]
        ,[D].[Q3_Score] AS [Score]
        ,[D].[Category]
    FROM [DataSet] AS [D]
) [upivot]
ORDER BY
    [UID]
    ,[Question]

... if you can use a new version of SQL with UNPIVOT then you can do this...

SELECT 
    [UID]
    ,SUBSTRING([Question],1,2) AS [Question]
    ,[Score]
    ,[Category]
FROM [DataSet]
UNPIVOT (
    [Score] FOR [Question] IN (
        [Q1_Score]
        ,[Q2_Score]
        ,[Q3_Score]
    )
) [upivot]

The results for either of the above is this...

UID Question    Score   Category
1   Q1              10  Science
1   Q2              7   Science
1   Q3              5   Science
2   Q1              9   Maths
2   Q2              6   Maths
2   Q3              10  Maths
3   Q1              0   History
3   Q2              3   History
3   Q3              4   History
4   Q1              3   English
4   Q2              1   English
4   Q3              4   English
Matthew Whited
  • 22,160
  • 4
  • 52
  • 69
1

You could create a new table using select with unions. If it needs to be the same table you could then drop the old one and create it from the new one.

select unique_id,'Q1' as 'Question', Q1_score as 'Score', Category
from table
union all
select unique_id,'Q2' as 'Question', Q2_score as 'Score', Category
from table
union all
select unique_id,'Q3' as 'Question', Q3_score as 'Score', Category
from table
order by unique_id, Question

--changed the group by to order by per Matthew Whited

NathanAck
  • 351
  • 3
  • 9
0

In this post of mine from just the other day, I demonstrate that the complex UNION ALL SELECT-s as seen above are not necessary - if you CROSS JOIN with an in-line table consisting of as many consecutive integers as you have horizontal columns to un-pivot. It works on any database that supports CROSS JOIN and the CASE .. WHEN clause:

How to create multiple rows from a initial row

vertical pivoting and "un-pivoting" mean the same.

And here, I take it to extremes:

Vertica - Is there LATERAL VIEW functionality?

In this post, I un-pivot a two-row table, then do something with the pivoted data, and then re-pivot it.

Happy playing ..

Community
  • 1
  • 1
marcothesane
  • 6,192
  • 1
  • 11
  • 21