Home > other >  How to sum one column if other have different value?
How to sum one column if other have different value?

Time:03-07

I have a table

clientId |    cns | cpf | value
       1 |      1 |   1 |     1
       1 |   null |   1 |     1

I need to sum the value column and get the not null value on column cns like this:

clientId |    cns | cpf | value
       1 |      1 |   1 |     2

The id field is not a primary key, is a clientId of other table. The field cpf sometimes have a value, sometimes have null.

Any idea?

CodePudding user response:

If cpf and cns only contain null or 1, you can use max or min to get the non-null values when you aggregate the value using group by

select id, 
       min(cns) as cns,
       min(cpf) as cpf,
       sum(value) as value
from the_table
group by id;

Aggregate functions ignore null values, that's why min(cns) will return the (smalles) not-null value across all rows.

  • Related