hamed khorasani
hamed khorasani

Reputation: 21

mysql - How do we get the sum of the values on two tables?

I have two tables

table: a
---------------------
id    amount  status
---------------------
4031  3000    1
4032  4000    1
4033  5000    1
4034  6000    1
4035  7000    1
4036  8000    0
table: s
--------------
id a_id  b_id 
--------------
1  4031  20
2  4031  21
3  4032  23
4  4032  24
5  4033  25
6  4033  26
7  4034  21
8  4034  20
9  4035  25
10 4035  29
11 4036  21
12 4036  20

How do we get the sum of the a.amount where have ( b_id = 20 AND b_id = 21) AND a.status = 1?

The answer should be 9000.

Upvotes: 0

Views: 52

Answers (4)

hamed khorasani
hamed khorasani

Reputation: 21

SELECT SUM(a.amount)
FROM a
WHERE a.status=1 AND
      EXISTS (SELECT 1
              FROM s
              WHERE s.a_id=a.id AND s.b_id=20) AND 
              EXISTS (SELECT 1
              FROM s
              WHERE s.a_id=a.id AND s.b_id=21) ;

Upvotes: 0

cdaiga
cdaiga

Reputation: 4939

You can get the answer using a subquery:

SELECT SUM(a.amount)
FROM a
WHERE a.status=1 AND
      EXISTS (SELECT 1
              FROM s
              WHERE s.a_id=a.id AND s.b_id in (20,21));

There is no need to group the data as we want the global sum of the amounts selected.

Upvotes: 0

Manash Kumar
Manash Kumar

Reputation: 1075

Try this:

select sum(a.amount)
from a 
join b on a.id = b.a_id 
where b.b_id IN ( 20, 21 ) and a.status = 1

Upvotes: 0

Moose
Moose

Reputation: 2737

SELECT SUM(amount) FROM (
JOIN s ON a.id = s.id
WHERE STATUS =1
AND (b_id = 20 OR b_id = 21) GROUP BY a.id
) AS amounts

total : 9000

In the case you can add several times the same amount, I guess this should work without join:

SELECT SUM(amount) AS total 
FROM `a`, `s` 
WHERE a_id = a.id AND (b_id = 20 OR b_id = 21) AND status = 1

total : 18000

Upvotes: 2

Related Questions