SQL sum column in one table where value in another table is 'S'

1.7k Views Asked by At

I have 2 tables:

[rolls]
tappi zone poids
N1001 101 502
N1002 102 502
N1003 103 1008
N1004 104 1008

[zones]
nom  type
101   P
102   P
103   S
104   S

What I want to do is sum 'rolls'.'poids' if 'rolls'.'zone' has the type 'S' (according to table 'zones')

Output should be 2016 (1008+1008)

2

There are 2 best solutions below

1
On BEST ANSWER
SELECT SUM(t1.poids)
FROM rolls t1
INNER JOIN zones t2
    ON t1.zone = t2.nom
WHERE t2.type = 'S'

We can safely do an INNER JOIN here because if a record from rolls does not match to anything in zones then we know that it cannot be zone type S.

2
On

SELECT SUM(rolls.poids) FROM rolls JOIN zones ON rolls.zone = zones.nom WHERE zones.types ='S';

By using JOIN we are looking for the the data that the rolls table and zones table have and by using ON we are limiting to find the data where they have an column in common. The goal here is to combine these tables. So that would happen:

[[rolls] JOINED [zones]]
tappi zone poids nom type
N1001 101 502    101 P
N1002 102 502    102 P
N1003 103 1008   103 S
N1004 104 1008   104 S

Using the where we would segment even more our query to find only records with type S. So now you are looking at:

[[rolls] JOINED [zones]]
tappi zone poids nom type
N1003 103 1008   103 S
N1004 104 1008   104 S

And even further you would be looking for this record and saying to yourself. I just want the sum of the poids. So then you use a SELECT SUM(rolls.poids) and the final result is:

[sum(rolls.poids)]
   2016