'Assign NULL to repeated values in different columns in SQL
I have a table like this:
| id | mail_1 | mail_2 | mail_3 |
|---|---|---|---|
| 1 | john | john_v2 | NULL |
| 2 | clarisse | clarisse | clarisse_company |
| 3 | NULL | julie | NULL |
| 4 | mark | markus_91 | mark |
| 5 | alfred | alfred | alfred |
And I would like to put NULLs where the mail is repeated, for example in the row 2 mail_1 and mail_2 have the same value; clarisse, and I would like to assign a NULL in mail_2. So I'm thinking in an algorithm that first fix the row and then go through the columns and check if the current value is the same as the previous. So the final table would be something like this:
| id | mail_1 | mail_2 | mail_3 |
|---|---|---|---|
| 1 | john | john_v2 | NULL |
| 2 | clarisse | NULL | clarisse_company |
| 3 | NULL | julie | NULL |
| 4 | mark | markus_91 | NULL |
| 5 | alfred | NULL | NULL |
Doing this with other languages is pretty easy, such Python or R, but I would like to have it done in SQL.
Any ideas? Thanks.
Solution 1:[1]
use case when
select id,mail_1,
case when mail_1=mail2 then null else mail_2 end as mail_2, mail_3
from table_name
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zaynul Abadin Tuhin |
