2016-06-14 2 views
3

표 1 (리포트)와 - 구조 - 데이터MySQL의 피벗 쿼리 열 값의 합

id distributor 
1  Dis A 
2  Dis B 
3  Dis C 
6  Dis D 

표 3 (클라이언트)와 구조 - 데이터

id distributorId clientId amount 
1  1   162 2500 
2  2   163 3500 
3  3   203 4500 
4  6   157 5500 
5  1   162 1500 
6  3   163 2000 
7  3   162 1000 

표 2 (대리점)와 구조

,691 : 데이터와

id client_name 
162  Client A 
163  Client B 
203  Client C 
157  Client D 
는 상기 사용 희망 출력

3 개 테이블을 정의 고정 피벗 SQL에 대한

client_name Dis A Dis B Dis C Dis D 
Client A  4000  0  1000  0 
Client B  0  3500 2000  0 
Client C  0  0  4500  0 
Client D  0  0  0  5500 
+0

은 무엇 당신의 문제? 쿼리를 해봤습니까? 오류가 무엇입니까? –

+1

Google : "MySQL 동적 피벗" –

+0

배급 업체 수는 고정되어 있습니까? –

답변

0

,이 시도 :

select 
    t.client_name, 
    sum(if(t.distributor = 'Dis A', t.amount, 0)) as `Dis A`, 
    sum(if(t.distributor = 'Dis B', t.amount, 0)) as `Dis B`, 
    sum(if(t.distributor = 'Dis C', t.amount, 0)) as `Dis C`, 
    sum(if(t.distributor = 'Dis D', t.amount, 0)) as `Dis D` 
from (
    select c.id, c.client_name, d.distributor, r.amount 
    from clients c 
    left join reports r on c.id = r.clientId 
    left join distributor d on d.id = r.distributorId 
)t 
group by t.id 
order by t.client_name 
동적 피벗 SQL에 대한

SQLFiddle DEMO HERE

는,이 시도 :

SET @sql = NULL; 
SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'sum(if(t.distributor = ''', 
     distributor, 
     ''', t.amount, 0)) AS `', 
     distributor ,'`' 
    ) 
) INTO @sql 
FROM distributor; 
SET @sql = CONCAT('SELECT t.client_name, ', @sql, ' FROM (
    select c.id, c.client_name, d.distributor, r.amount 
    from clients c 
    left join reports r on c.id = r.clientId 
    left join distributor d on d.id = r.distributorId 
)t 
group by t.id 
order by t.client_name'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

SQLFiddle DEMO HERE