SQL - 在列中选择相同的值,然后重命名它们

时间:2015-11-03 14:24:37

标签: mysql sql

在SQL中是否可以选择列中的值然后重命名重复的值? (假设最多只有一个可能的重复)

假设我有一张桌子..

| id | name  | 0or1_id |
| 0  | Eddy  | 0       |
| 1  | Allan | 0       |
| 2  | Eddy  | 1       |
| 3  | Allan | 1       |

我可以做什么查询来实现这个目标?

| id | name       | 0or1_id |
| 0  | Eddy       | 0       |
| 1  | Allan      | 0       |
| 2  | Eddy-copy  | 1       |
| 3  | Allan-copy | 1       |

3 个答案:

答案 0 :(得分:0)

这将在SQL Server中运行..

select id , name ,0or1_id from (
select id , name ,0or1_id ,row_number() over (partition by name order by id ) as rnm
from table)z1
where rnm =1
union 
select id , name || '- Copy' as new_name ,0or1_id from (
select id , name ,0or1_id ,row_number() over (partition by name order by id ) as rnm
from table)z2
where rnm > 2

答案 1 :(得分:0)

假设您要实际更改数据,请使用update

update t join
       (select name, count(*) as cnt, min(id) as minid
        from t
        group by name
        having cnt > 1
       ) tt
       on t.name = tt.name and t.id <> tt.minid
    set name = concat(name, '-copy');

如果你只想要一个select,那么逻辑非常相似。

答案 2 :(得分:0)

http://sqlfiddle.com/#!9/3ebaf/1

UPDATE mytable t
INNER JOIN mytable t1
ON t.name = t1.name
  AND t.id>t1.id
SET t.name = CONCAT(t.name,'-copy');