0

I am trying to get the the sum value of a column but this value changes according to a condition.

If I have a particular value in the column 'splits', the I need to have something like this:

SELECT sum(weight) 
from table 
WHERE 'STR' in splits

Otherwise I only need:

SELECT sum(weight) 
from table

I haven't been able to do this correctly and I really need a bit of help!

  • 3
    Please **[edit]** your question (by clicking on the [edit] link below it) and add some [sample data](https://meta.stackexchange.com/questions/81852) and the expected output based on that data. [Formatted text](https://meta.stackoverflow.com/a/251362) please, [no screen shots](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557). ([edit] your question - do **not** post code or additional information in comments) –  Jul 08 '19 at 08:40
  • Possible duplicate of [Is it possible to specify condition in Count()?](https://stackoverflow.com/questions/1400078/is-it-possible-to-specify-condition-in-count) – Joakim Danielson Jul 08 '19 at 08:51

2 Answers2

0

This is the only reasonable interpretation I can make of the question:

SELECT (CASE WHEN splits LIKE '%STR%' THEN 1 ELSE 0 END) as has_str,
       SUM(weight) 
FROM table 
GROUP BY (CASE WHEN splits LIKE '%STR%' THEN 1 ELSE 0 END);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-1

If i understand your case corretly, you only need to change the where clause to in() like that:

SELECT sum(weight) 
from table 
WHERE splits in('STR')

I Dont know which DBMS you are using, but that should work with most of them.

Kevin Böhmer
  • 462
  • 4
  • 21