我有一个非常简单的问题,我正在尝试解决,但无法解决它。
我有三个结构相同的表
t1.id, t1.cust_id, t1.name, t1.value
t2.id, t2.cust_id, t2.name, t2.value
t3.id, t3.cust_id, t3.name, t3.value
客户出现在某些表中,但不出现在其他表中;每个中的“值(value)”记录都是美元金额。
我想在 mySQL 中运行一个查询,生成一个汇总表,将三个表中每个客户的所有购买情况相加。
我想要的输出看起来像这样:
Name Customer ID T1 T2 T3
Joe 88888 12.45 45.90 2.34
Ted 99999 8.90 3.45 null
Sue 12123 9.45 2.45 null
我尝试了一些使用 JOIN 的查询,但没有得到满意的结果。
感谢您的帮助!
最佳答案
使用union all
组合3个表中的行,然后使用聚合。
select cust_id,name,sum(t1val),sum(t2val),sum(t3val)
from (
select id, cust_id, name, value as t1val, null as t2val, null as t3val from t1
union all
select id, cust_id, name, null, value, null from t2
union all
select id, cust_id, name, null, null ,value from t3
) t
group by cust_id,name
关于mysql - 将三个 mysql 表中的员工值相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42660684/