简体   繁体   中英

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

You need to express this as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM