Search code examples
sqlinformix

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


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)


Solution

  • 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.