2017-03-08 40 views
0

我有一个非常简单的问题,我正在努力解决,但无法绕过它。在三个mysql表中为员工加起来的价值

我有相同的结构

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 

客户出现在某些表,但不是在其他的三个表;每个“价值”记录都是美元数量。

我想在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 

我已经尝试了一些查询连接,但没有令人满意的结果。

感谢您的帮助!

回答

1

使用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 
+0

不错!谢谢,这似乎运作良好。 – tomish

0

你可以用SELECT做到这一点,例如:

SELECT (
     (SELECT COALESCE(SUM(value),0) FROM t1 WHERE cust_id = 100) 
     + 
     (SELECT COALESCE(SUM(value),0) FROM t2 WHERE cust_id = 100) 
     + 
     (SELECT COALESCE(SUM(value),0) FROM t3 WHERE cust_id = 100) 
    ) as total; 

这里的SQL Fiddle

+0

感谢您的答复,但我将不得不用实际的客户ID替换问号,对吗?我想这可能是对表1 2和3的子查询? – tomish

+0

@tomish我已经用示例更新了查询。是的,我们需要把客户ID,这些是简单的选择查询,而不是子查询。 –

+0

谢谢Darshan! – tomish