简体   繁体   English

将SUM函数与SQL连接一起使用

[英]Use SUM function with SQL joins

Let consider two tables as shown below: 让我们考虑两个表,如下所示:

              table_a            table_b
          ----------------    ---------------      
          |Name | link_id |   | id | amount |  
          -----------------   ---------------
          | M   |  2      |   | 2  | 100    |
          | N   |  3      |   | 3  | 20     |
          | M   |  2      |   | 2  | 10     |
          ----------------    | 3  | 200    |   
                              ----------------

Now I want to get user name and sum of amount he has. 现在我想获得用户名和他拥有的金额总和。 The expected out put should be: 预期的出局应该是:

           -----------------------         
          |Name | his_sum_amount |
          ------------------------
          | M   |  110           | 
          | N   |  220           |
           -----------------------

For that I have written a query as shown below: 为此我写了一个查询,如下所示:

select name,sum(amount) from table_a inner join table_b on table_a.link_id=table_b.id; 

But above query is giving whole sum of amount, how can I get individual sum. 但是上面的查询给出了全部金额,我怎样才能获得个别金额。

In most databases your query would generate an error, because of name in the select . 在大多数数据库中,由于selectname ,您的查询会生成错误。

You are simply missing group by : 您只是缺少group by

  select name, sum(amount)
  from table_a inner join
       table_b
       on table_a.link_id = table_b.id
  group by name;

Use GROUP BY to SUM by name. 按名称使用GROUP BYSUM

SELECT a.name, SUM(b.amount) AS his_sum_amount
FROM table_a a 
INNER JOIN table_b b ON a.link_id = b.id
GROUP BY a.name

Output 产量

name  his_sum_amount
M     220
N     220

SQL Fiddle: http://sqlfiddle.com/#!9/00085/1/0 SQL小提琴: http ://sqlfiddle.com/#! 9/00085/1/0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM