0

Right now I have the following table and I want to unpivot it so my columns and rows are flipped like below - thank you!

HAVE

current

WANT

want

Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
Meaghan
  • 19
  • 1
  • 1
  • 1
    What DBMS are you using and what have you tried? – Aura Oct 12 '18 at 20:17
  • 1
    Welcome to Stack Overflow. Your question doesn't include enough useful detail for us to help you. Check out [How To Ask](https://stackoverflow.com/help/how-to-ask) and the importance of a [Minimal, Complete, Verifiable Example](https://stackoverflow.com/help/mcve). After that, [Start Here](https://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/) to edit your question as needed. Also, [avoid pictures of code...](https://meta.stackoverflow.com/a/285557/5790584) – Eric Brandt Oct 12 '18 at 21:34
  • 1
    Possible duplicate of [Unpivot with column name](https://stackoverflow.com/questions/19055902/unpivot-with-column-name) – Eric Brandt Oct 12 '18 at 21:36

1 Answers1

3

This example is in Transact-SQL. The Oracle (11g+) syntax is similar but with a few more options, such as how to treat null values.

-- setting up a table variable with your starting data
declare @t table 
    (  Name         varchar(10) primary key 
      ,[Age 18-24]  int
      ,[Age 25-34]  int
      ,[Age 35-44]  int  );

insert @t (Name, [Age 18-24], [Age 25-34], [Age 35-44])
values   ('John', 1, 0, 0 )
        ,('Maria', 0, 0, 1 )
        ,('June' , 0, 0, 1 )

--- the actual query starts here 

select [Name], [Column], [Value]
from 
    (   -- select relevant columns from source 
        select Name, [Age 18-24], [Age 25-34], [Age 35-44]
        from @t
    ) as piv
UNPIVOT
    (   -- define new result columns.  
        ----  [Value] is the detailed count/sum/whatever
        ----  [Column] get the old name of the column 

        [Value] 
        for [Column] in ([Age 18-24], [Age 25-34], [Age 35-44]) 
    ) as unpiv
Cameron S
  • 79
  • 5