简体   繁体   中英

PostgreSQL: using case to compare values between columns

I would like to compare two columns, A and B.

If Col A and Col B share the same value, I would like Col A to have a no value set. If Col A and Col B do not share the same value, I would like Col A to keep the original value it has.

Below is what I attempted. However, it returns "true" for all entries in the case column - Col A (corrected).

select *,
    case when 'Col A' = 'Col B' 
        then 'Col A' = null 
        else 'Col A' = 'Col A'
        end as "Col A (corrected)"
from my_table
select
  case
   when col_a=col_b then null
   else col_a
 end as col_a_corrected
from my_table

Simply do

select *,
       NULLIF(col_a, col_b)
from my_table

The NULLIF returns null if col_a = col_b, otherwise col_a is returned.

https://www.postgresql.org/docs/current/functions-conditional.html#FUNCTIONS-NULLIF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM