1

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.

1
  • I guess you meant 'M','N', not '2','3' Commented Jun 6, 2016 at 13:13

2 Answers 2

3

In most databases your query would generate an error, because of name in the select.

You are simply missing group by:

  select name, sum(amount)
  from table_a inner join
       table_b
       on table_a.link_id = table_b.id
  group by name;
Sign up to request clarification or add additional context in comments.

Comments

0

Use GROUP BY to SUM by name.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.