1

SQL noob here. I want to sum two columns separately, using 2 separate where conditions.

ID  NAME    VALUE1   VALUE2
--- ------- -------  -------
1   Orange  5        30
2   Orange  11       30
3   Orange  7        15 
4   Pear    12       12 
5   Pear    13       25 
6   Pear    4        25 
  • Sum of VALUE1 column where values are > 10
  • Sum of VALUE2 column where values are > 20
  • Grouped by NAME

Desired output:

NAME    VALUE1   VALUE2
------- -------  -------
Orange  11       60
Pear    25       50 

Thanks!

2 Answers 2

2

Use conditional aggregation:

select name, sum(case when value1 > 10 then value1 end),
       sum(case when value2 > 20 then value2 end)
from t
group by name;
Sign up to request clarification or add additional context in comments.

Comments

0

I know this approach is bit tricky and lengthy as well,however this might be helpful in debugging ,if you can try this :

select 
value1.name,value1.a,value2.b 
from 
(select sum(value1)a,name from test where value1 >10 group by name) as value1
join (select sum(value2)b,name from test where value2 >20 group by name) as value2
on value1.name = value2.name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.