表1(报告) - 带数据的结构
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(经销商) - 带数据的结构
id distributor
1 Dis A
2 Dis B
3 Dis C
6 Dis D
表3(客户) - 带数据的结构
id client_name
162 Client A
163 Client B
203 Client C
157 Client D
期望输出使用上面定义的3个表:
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)
对于fixed pivot sql,请尝试:
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,请尝试以下方法:
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;