SQL - detect duplicate in a column only if they matter in another column
I have this MYSQL table:
Name | Age | X
--------------------
Andrew | 7 |
Andrew | 7 |
Andrew | 10 |
John | 9 |
John | 11 |
John | 11 |
And I would like to assign a value to those names that share age, for example:
Name | Age | X
--------------------
Andrew | 7 | x
Andrew | 7 | x
Andrew | 10 |
John | 9 |
John | 11 | x
John | 11 | x
I don’t know how to do it.
+3
source to share
4 answers
If your database supports functions window
, then
Select Name,Age,
case when count(Age)over(partition by Name, Age) > 1 then 'x' else '' end as X
FROM yourtable
If no ( Mysql
), then
Select Name,Age,
case when (select count(Age) from yourtable b where a.Name = b.Name and a.Age = b.Age) > 1 then 'x' else '' end as X
FROM yourtable a
+2
source to share