如何选择出现在两个表中的实体的总和

问题描述

我有两种类型的牵引力表,一个用户可以出现在一个或两个表中,我的目标是获得每个用户的总和。表格如下。

 users
------------+----------+
| user_id   | Name     |
+-----------+----------+
| 1         | John     |
------------+----------+
| 2         |  Wells   |
------------+----------+

 shop1
------------+----------+--------------+
| trans_id  | user_id  | amount_spent |
+-----------+----------+--------------+
| 1         |   1      |   20.00      |
------------+----------+--------------+
| 2         |   1      |   10.00      |
------------+----------+--------------+

 shop2
------------+----------+--------------+
| trans_id  | user_id  | amount_spent |
+-----------+----------+--------------+
| 1         |   2      |   20.05      |
------------+----------+--------------+

求和后的预期结果

------------+-------------+
| user      | Total Spent |
+-----------+-------------+
| John      |   30.00     |
------------+-------------+
| Wells     |   20.05     | 
------------+-------------+

解决方法

您可以使用union all和聚合:

select user_id,sum(amount_spent) total_spent
from (
    select user_id,amount_spent from shop1
    union all
    select user_id,amount_spent from shop2
) t
group by user_id
,

使用union allgroup by

select user_id,sum(amount_spent)
from ((select user_id,amount_spent from shop1) union all
      (select user_id,amount_spent from shop2)
     ) s
group by user_id;

也就是说,您的数据模型很差。通常,具有相同列的表是一个非常糟糕的主意。您应该为所有商店使用一个表格,并为商店增加一列。

如果要使用名称,则需要join

select u.name,sum(amount_spent)
from users u join
     ((select user_id,amount_spent from shop2)
     ) s
     using (user_id)
group by user_id,u.name;
,
select user_id,sum(amount_spent)
from
(shop1
UNION ALL
ship2)
group by user_id