SQL - 仅当列中的副本与另一列中的值共享时才检测列中的副本

时间:2017-06-29 10:22:26

标签: mysql sql

我有这个MYSQL表:

Name    |  Age | X
--------------------
Andrew  |   7  |
Andrew  |   7  |
Andrew  |  10  |  
John    |   9  |
John    |  11  | 
John    |  11  |

我想为那些分享年龄的名字分配一个值,如下所示:

Name    |  Age | X
--------------------
Andrew  |   7  | x
Andrew  |   7  | x
Andrew  |  10  |  
John    |   9  |
John    |  11  | x
John    |  11  | x

不知道该怎么做。

4 个答案:

答案 0 :(得分:2)

如果您的数据库支持window功能,那么

Select Name,Age,
       case when count(Age)over(partition by Name, Age) > 1 then 'x' else '' end as X
FROM yourtable 

如果不是(Mysql),那么

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    

答案 1 :(得分:1)

由于MySQL不支持窗口函数,因此必须读取表格两次。这是一种方法:

select name, age, dups.x
from persons p
left join
(
  select name, age, 'x' as x
  from persons
  group by name, age
  having count(*) > 1
) dups using (name, age)
order by name, age;

答案 2 :(得分:0)

- 检测所有列的重复列

    with cte as
    (select name, age ,x , row_number () over (partition by name,age,x order by 
   name) RowNum from Table 
    ) select name,age,x from cte where rownum > 1

答案 3 :(得分:0)

肯定这个会工作。试试吧...... :)。简单明了!

   Select Name,Age,count(*)   
   INTO #TempTable 
   FROM yourtable 
   group by   Name,Age
   having count(*) >1


update a 
set a.X= "X"
from yourtable a 
      join #TempTable b on  a.Name=b.Name and a.Age =b.Age

drop table #TempTable