让我们考虑两个表,如下所示:
table_a table_b
---------------- ---------------
|Name | link_id | | id | amount |
----------------- ---------------
| M | 2 | | 2 | 100 |
| N | 3 | | 3 | 20 |
| M | 2 | | 2 | 10 |
---------------- | 3 | 200 |
----------------
现在,我想获取用户名和他拥有的总金额。预期的输出应该是:
-----------------------
|Name | his_sum_amount |
------------------------
| M | 110 |
| N | 220 |
-----------------------
为此,我编写了一个查询,如下所示:
select name,sum(amount) from table_a inner join table_b on table_a.link_id=table_b.id;
但是上面的查询给出了全部金额,我怎么才能得到单个金额。
在大多数数据库中,由于name
中的原因,您的查询会生成错误select
。
您只是想念group by
:
select name, sum(amount)
from table_a inner join
table_b
on table_a.link_id = table_b.id
group by name;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句