nomnom3214
nomnom3214

Reputation: 259

How to sum with two conditions in sql?

type     category      value
alpha     stone          2
alpha     soil           3
alpha     water          2
beta      stone          3
beta      soil           4
beta      water          4

I want to sum when the type is alpha and the category is stone, and also when the type is beta and the category is water.

What I have tried was:

select
   type,
   sum(value)
from
   table1
where true
   and type in ('alpha', 'beta')
   and category in ('stone', 'water')
group by
   type

From the query above, I got 11. Meanwhile, it supposed to be 6. This query also sum the water from alpha and also stone from beta. How should I write my query to get the desired result? Thanks in advance

Upvotes: 0

Views: 66

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

You need to express this as:

select sum(value)
from table1
where (type = 'alpha' and category = 'stone') or
      (type = 'beta' and category = 'water');

Upvotes: 2

Related Questions