SQL将聚合值转换为单个列

时间:2017-02-14 06:39:23

标签: sql oracle oracle11g transform transpose

所以我现在有这样的数据标准化:

+----------+-------+-------+
| day      | color | value |
+----------+-------+-------+
| 1/1/2016 | red   | 1     |
+----------+-------+-------+
| 1/1/2016 | blue  | 2     |
+----------+-------+-------+
| 1/1/2016 | green | 3     |
+----------+-------+-------+
| 1/2/2016 | red   | 4     |
+----------+-------+-------+
| 1/2/2016 | blue  | 5     |
+----------+-------+-------+
| 1/2/2016 | green | 6     |
+----------+-------+-------+  

我想将其转换为此报告的布局:

+----------+-----+------+-------+
| day      | red | blue | green |
+----------+-----+------+-------+
| 1/1/2016 | 1   | 2    | 3     |
+----------+-----+------+-------+
| 1/2/2016 | 4   | 5    | 6     |
+----------+-----+------+-------+  

我用来执行此操作的代码是:

with
red as (
    select
    day
    ,value as red
    from mytable
    where color='red'
),

blue as (
    select
    day
    ,value as blue
    from mytable
    where color='blue'
),

green as (
    select
    day
    ,value as green
    from mytable
    where color='green'
)

select
red.*
,blue.blue
,green.green
from red red
inner join blue blue
on red.day=blue.day
inner join green green
on red.day=green.day  

所以我的问题是,在Oracle中有更简单或更少的罗嗦方式吗?这么简单的任务似乎有点傻了!而且,它可能效率不高。

1 个答案:

答案 0 :(得分:2)

希望,我理解你的问题。

我认为以下查询会对您有帮助。

select day_col,
max(case when color = 'red' then value_col end) red_color,
max(case when color = 'blue' then value_col end) blue_color,
max(case when color = 'green' then value_col end) green_color
from your_table 
group by day_col;