Home > Software engineering >  How to sum the values of the column in postgresql on a certain condition?
How to sum the values of the column in postgresql on a certain condition?

Time:06-20

I have a table, that looks something like this:

Name    | Val_Num
--------------------
Joey    | 1
Joey    | 2
Chandler| 2 
Monica  | 3
Monica  | 2

What I need is to make a select in which I'll remove from dublicates in names and sum up the values in Val_Num (but the sum up should use simple formula - if value is 1 add 1, if value is not 1 add 0.5). Result of the query should look like this:

Name    | Val_Num
--------------------
Joey    | 1.5
Chandler| 0.5 
Monica  | 1

Looking forward for your help, thanks.

CodePudding user response:

Use a CASE expression in order to decide when to add 1 and when 0.5.

SELECT Name, SUM(CASE WHEN Val_Num = 1 THEN Val_Num ELSE 0.5 END)
FROM test_table
GROUP BY Name

CodePudding user response:

You can use CASE WHEN statement to replace all values that are not 1 with 0.5, and then do a simple GROUP BY query

select name, sum(case when val_Num !=1 
    then 0.5 else val_Num end 
) from table_1 group by name

Demo in DBfiddle

  • Related