[英]MySQL Pivot Query with Sum of column value
Table 1(reports) - Structure with Data表 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
Table 2(distributor) - Structure with Data表 2(分销商)- 数据结构
id distributor
1 Dis A
2 Dis B
3 Dis C
6 Dis D
Table 3(clients) - Structure with Data表 3(客户端)- 数据结构
id client_name
162 Client A
163 Client B
203 Client C
157 Client D
Desired Output Using the above defined 3 tables:所需的 Output 使用上面定义的 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
For the fixed pivot sql, try this: 对于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
SQLFiddle DEMO HERE SQLFiddle DEMO HERE
For the dynamic pivot sql, try this: 对于动态pivot 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;
Try this one.试试这个。
with new_table as
(
select
T3.client_name as client,
sum(case when T1.distributorId = '1 ' then amount end) as 'Dis A',
sum(case when T1.distributorId = '2 ' then amount end) as 'Dis B',
sum(case when T1.distributorId = '3 ' then amount end) as 'Dis C',
sum(case when T1.distributorId = '6 ' then amount end) as 'Dis D'
FROM reports T1
JOIN distributor T2 on T2.id = T1.distributorId
JOIN clients T3 on T3.id = T1.clientId
)
select
client,
Dis A ,
Dis B,
Dis C,
Dis D
FROM New_Table
group by 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.