具有列值总和的MySQL Pivot查询
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了具有列值总和的MySQL Pivot查询,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1789字,纯文字阅读大概需要3分钟。
内容图文
![具有列值总和的MySQL Pivot查询](/upload/InfoBanner/zyjiaocheng/903/63be73c2ad284e498bd59f24ef3e3b60.jpg)
表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
解决方法:
对于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
对于动态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;
内容总结
以上是互联网集市为您收集整理的具有列值总和的MySQL Pivot查询全部内容,希望文章能够帮你解决具有列值总和的MySQL Pivot查询所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。