离散值的非旋转直方图数据

时间:2017-03-05 06:04:39

标签: sql netezza

使用表grades保存下面学生的成绩直方图,需要取消将列名称转换为索引。

CREATE TABLE grades
AS
  SELECT name, exams, grade_poor, grade_fair, grade_good, grade_vgood
  FROM ( VALUES
    ( 'arun'  , 8  , 1 , 4 , 2 , 1 ),
    ( 'neha'  , 10 , 3 , 2 , 1 , 4 ),
    ( 'ram'   ,  5 , 1 , 1 , 3 , 0 ),
    ( 'radha' ,  8 , 0 , 3 , 1 , 4 )
  ) AS t(name,exams,grade_poor,grade_fair,grade_good,grade_vgood);

成绩可以索引为数值 - 例如,如下所示。

+-------------+--------+
|    grade    |  value |
+-------------+--------+
| grade_poor  |      1 |
| grade_fair  |      2 |
| grade_good  |      3 |
| grade_vgood |      4 |
+-------------+--------+

预期输出

+-------+-------+
| name  | grade |
+-------+-------+
| arun  |     1 |
| arun  |     2 |
| arun  |     2 |
| arun  |     2 |
| arun  |     2 |
| arun  |     3 |
| arun  |     3 |
| arun  |     4 |
| neha  |     1 |
| neha  |     1 |
| neha  |     1 |
| neha  |     2 |
| neha  |     2 |
| neha  |     3 |
| neha  |     4 |
| neha  |     4 |
| neha  |     4 |
| neha  |     4 |
| radha |     2 |
| radha |     2 |
| radha |     2 |
| radha |     3 |
| radha |     4 |
| radha |     4 |
| radha |     4 |
| radha |     4 |
| ram   |     1 |
| ram   |     2 |
| ram   |     3 |
| ram   |     3 |
| ram   |     3 |
+-------+-------+

问题和回答here显示了postgres的做法。

1 个答案:

答案 0 :(得分:0)

试试这个:

with up_grades as (
    select
        g.name,
        x.i grade_type,
        case x.i
            when 1 then grade_poor
            when 2 then grade_fair
            when 3 then grade_good
            when 4 then grade_vgood
        end grades
    from grades g
    cross join (
        select 1 i union all
        select 2 i union all
        select 3 i union all
        select 4 i  
    ) x
) 
select g.name, g.grade_type
from up_grades g
join (
    select level n
    connect by 
        level <= (select max(grades) from up_grades)
) c on g.grades >= c.n
order by g.name, g.grade_type;

在CTE内部,我们对表格进行解包,即将列转换为行。然后,我们使用分层查询来生成尽可能多的行,其中包含给定名称和成绩类型的等级。

免责声明 - Tested only on Oracle(在地方添加所需的双表后),因为语法大多匹配。在Netezza上未经测试。