이와 같은 문제로 저도 고민한 적이 있었는데,
저는 outer join 에서 힌트를 얻었습니다.
outer join 을 사용하려면, 기준이 되는 특정 로우에는 모든 데이터가
있어야하는지라, 일단, (A1 열을 기준으로
(x,y) 표시,
(A1, A1), (A3,A1) 두 데이를 일단 0으로 임의로 입력했습니다.
다음,
select a.f1,
a."A1",
case when b."A2" is null then '0' else b."A2" end as "A2",
case when c."A3" is null then '0' else c."A3" end as "A3",
case when d."A4" is null then '0' else d."A4" end as "A4",
case when e."A5" is null then '0' else e."A5" end as "A5"
from
(select f1, val as "A1" from t where f2 = 'A1') a
left outer join
(select f1, val as "A2" from t where f2 = 'A2') b on a.f1 = b.f1
left outer join
(select f1, val as "A3" from t where f2 = 'A3') c on a.f1 = c.f1
left outer join
(select f1, val as "A4" from t where f2 = 'A4') d on a.f1 = d.f1
left outer join
(select f1, val as "A5" from t where f2 = 'A5') e on a.f1 = e.f1
이상과 같은 같은 쿼리라면, 원하는 모습 그대로 나올 것입니다.
달리 더 좋은 방법이 있으시면 알려주세요.
-- 이성한 님이 쓰신 글:
>> 안녕하십니까... 이성한 입니다.
>>
>> 다음과 같은 data가 있습니다.
>>
>> ===============================================
>> 이동구분1 이동구분2 이동가격
>> ===============================================
>> A1 A2 200
>> A1 A3 400
>> A1 A4 600
>> A2 A1 100
>> A2 A4 300
>> A2 A5 500
>> A3 A2 20
>> A3 A4 40
>> A3 A5 60
>> A4 A1 10
>> A4 A2 30
>> A4 A5 50
>> A5 A1 1
>> A5 A2 2
>> A5 A3 3
>> A5 A4 4
>>
>>
>> 위 data 가 존재시
>>
>> SQL 문장과 postgres 내부함수를 이용하여
>>
>> 다음과 같은 결과의 metrix 형태로 표시할 수 있는 방법이 궁굼합니다.
>>
>>
>> ----------------- 결과 ----------------------
>>
>> | A1 | A2 | A3 | A4 | A5
>> ----+-------+------+------+------+------
>> A1 | 0 | 200 | 400 | 600 | 0
>> ----+-------+------+------+------+------
>> A2 | 100 | 0 | 0 | 300 | 500
>> ----+-------+------+------+------+------
>> A3 | 0 | 20 | 0 | 40 | 60
>> ----+-------+------+------+------+------
>> A4 | 10 | 30 | 0 | 0 | 50
>> ----+-------+------+------+------+------
>> A5 | 1 | 2 | 3 | 4 | 0
>> ----+-------+------+------+------+------
>>
>> 그럼 수고 하십시오.
|