2014-04-08 3 views
0

검색했지만이 시나리오에 대한 답변을 찾을 수 없습니다. 나는 2.5 mil 행의 계좌를 가지고있는 테이블을 가지고있다. 이러한 계정은 각각 최소 3 회 이상 나타나며 영숫자 식별자 account_id로 식별됩니다. 계정 당 3 행은 3 개의 문자열 값 중 하나 (우리는 '1, 2 및 3'을 호출합니다)와 숫자 식별자 인 distributor_id를 포함하는 2 개의 열 profile_name을 제외하고 모두 식별됩니다. 구조는 다음과 같다 (이 분야에 국한되지하지만 그들은 내가 걱정하는 것입니다) :열 값을 기반으로 행을 결합하는 자체 조인을 작성하려면 어떻게해야합니까?

account_id  distributor_one_id distributor_two_id distributor_three_id 
    PX198   123     987     573 
    AZ476   123     652     NULL 
: 나는 이런 식으로 뭔가를 반환하는 쿼리를 조인 자체를 쓸 수있는 방법을

account_id  profile_name  distributor_id 
PX198    'one'    123 
PX198    'two'    987 
PX198    'three'    573 
AZ476    'one'    123 
AZ476    'two'    652 

내 질문은 당신은 최대 세 profile_names에서 할 수있는 경우

답변

2

당신은보다 효율적인 방법으로이 작업을 수행 할 수 있습니다

SELECT 
    account_id, 
    MAX(CASE WHEN profile_name = 'one' THEN distributor_id END) as distributor_one_id, 
    MAX(CASE WHEN profile_name = 'two' THEN distributor_id END) as distributor_two_id, 
    MAX(CASE WHEN profile_name = 'three' THEN distributor_id END) as distributor_three_id 
FROM tbl 
GROUP BY account_id 

SQL FIDDLE DEMO

2

,이 같은 테이블에 가입 할 수 :

SELECT 
    t1.account_id, 
    t1.distributor_id AS distributor_one_id, 
    t2.distributor_id AS distributor_two_id, 
    t3.distributor_id AS distributor_three_id 
FROM 
    yourtable t1 LEFT JOIN yourtable t2 
    ON t1.account_id = t2.account_id 
    AND t2.profile_name = 'two' 
    LEFT JOIN yourtable t3 
    ON t1.account_id = t3.account_id 
    AND t3.profile_name = 'three' 
WHERE 
    t1.profile_name = 'one' 

이 바이올린 here를 참조하십시오.

관련 문제