0

I have a table that looks like this:

Name   | Math   | English  | Arts
----------------------------------------
Brad   | 87     | 65       | 90
Julie  | 91     | 88       | 92

And I want to get:

Name  | Grade
--------------
Brad  | 87
Brad  | 65
Brad  | 90
Julie | 91
Julie | 88
Julie | 92

What's the simplest way to do that using SQL/Hive?

shakedzy
  • 2,853
  • 5
  • 32
  • 62

3 Answers3

1

Something like this.

select name,math as Grade from your_table
union all
select name,English as Grade from your_table
union all
select name,Arts as Grade from your_table
Utsav
  • 7,914
  • 2
  • 17
  • 38
1
select
  t.name, 
  CASE rows.col_name
    WHEN 'Math' THEN t.Math
    WHEN 'English' THEN t.**math** 
    WHEN 'Arts' THEN t.Arts
  end as Grade
from the_table t, 
     (select 'Math' as col_name
      union all 
      select 'English' as col_name
      union all 
      select 'Arts' as col_name) rows
StanislavL
  • 56,971
  • 9
  • 68
  • 98
1

You could use unpivot:

SELECT X.Name, X.Grade
FROM your_table s
UNPIVOT
(
  Grade
  FOR Subject in (Maths, English, Arts)
) X;

If you want to have the subject in the result add X.Subject into the select statement.

Vincent Pan
  • 246
  • 1
  • 7
  • I can get ot to run on Hive, are you sure it supports `UNPIVOT`? I also assume it's `as` after `your_table` – shakedzy Aug 24 '16 at 13:39
  • 1
    Sorry, I'm not too clear about Hive. I answered it with respect to solving it using SQL. [link](http://stackoverflow.com/questions/32621970/hive-unpivot-functionality-in-hive) has an unpivot in Hive example which may help. – Vincent Pan Aug 25 '16 at 00:29