SQL:基于列的重复行

时间:2016-08-24 12:27:28

标签: sql hiveql

我有一个看起来像这样的表:

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

我想得到:

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

使用SQL / Hive最简单的方法是什么?

3 个答案:

答案 0 :(得分:1)

像这样。

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

答案 1 :(得分: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

答案 2 :(得分:1)

您可以使用unpivot

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

如果您想让结果中的主题添加X.Subject到select语句中。