SQL은

2017-02-14 1 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  | 
+----------+-----+------+-------+ 

코드 I

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'값이있는 경우 'SUM()'보다 'MAX()'를 사용하는 것이 더 좋습니다. –

+0

아, 고마워, 나는이 대답이 내가 찾고있는 것이라고 믿지만 MAX()와 같이 말했다. :) – barker

+0

미안하지만, 내가 틀렸다면 그냥 sum을 max로 바꿔라. 쿼리를 업데이트했습니다. – Tajinder