Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PostgreSQL: Compare and change values in the same column based on conditions

I have data in the form:

Name   Category  my_value
Ana    A         42
Ana    B         33
Bob    A         33
Bob    B         33
Carla  A         42
Carla  B         33

I would like the following to happen for the same Name:

  • when A and B share the same value, A has no value associated to it (in col my_alue).
  • when A an B are different, A keeps its value and B has no value associated to it (in col my_value).

I’ve attempted:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select *,
    case when Category = 'A' and Category = 'B' 
        then my_value = null
        else my_value
        end as "Value A (corrected)"
from my_table

Obviously wrong… not sure how I can also implement the condition to set B as null if the values are different. And how to implement a group by here to compare the categories for the same name…

Ideally, This is the output I’m after (changes in the same column as I have more categories for each name in it, i.e. C, D, E… – only need changes in A and B)

Name   Category  Value
Ana    A         42                      
Ana    B                                 
Bob    A                                 
Bob    B         33                                       
Carla  A         42    
Carla  B                                   

>Solution :

Join to itself where the other row is the A/B compliment:

select
  t1.Name,
  t1.Category,
  case
    when t1.my_value = t2.my_value and t1.Category = 'A' then null
    when t1.my_value != t2.my_value and t1.Category = 'B' then null
    else t1.my_value
  end as my_value
from my_table t1
left join my_table t2 on t2.Name = t1.Name
  and t2.Category != t1.Category
  and t2.Category in ('A', 'B')
  and t1.Category in ('A', 'B')

See live demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading