2017-02-14 28 views
0

所以我有數據標準化這樣目前:SQL變換合計值到各個列

+----------+-------+-------+ 
| 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 

所以我的問題是,是否有一個更容易或不那麼羅嗦的方式來做到這一點在甲骨文?對於這樣一個簡單的任務似乎有點愚蠢!另外,這可能不是很有效。

回答

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; 
+0

如果他的實際數據集中包含「NULL」值,則最好使用比MAX()更多的'MAX()'。 –

+0

啊謝謝,我相信這個答案是我正在尋找的,但是像MAX()這樣的tim說道。 :) – barker

+0

對不起,如果我錯了,只需用max取代sum。我已更新查詢。 – Tajinder