如何索引列中具有重复值的行?

m3eecexj  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(273)

我怎样才能把重复的数进去 Phone ?
例如:

State   Zip Areacode    Phone
A       123 1           989
b       234 2           989
c       345 3           989
d       456 4           123
e       567 5           123
f       678 6           234
g       678 7           234

预期结果:

State   Zip Areacode    Phone   row_count
A       123 1           989     1
b       234 2           989     2
c       345 3           989     3
d       456 4           123     1
e       567 5           123     2
f       678 6           234     1
g       678 7           234     2
vdgimpew

vdgimpew1#

下面是通过比较多个列来查找重复记录的mysql查询

SELECT 
    Zip, COUNT(Zip),
    Areacode,  COUNT(Areacode),
    Phone,      COUNT(Phone)
FROM
    TableName
GROUP BY 
    Zip , 
    Areacode , 
    Phone
HAVING  COUNT(Zip) > 1
    AND COUNT(Areacode) > 1
    AND COUNT(Phone) > 1;

从mysql表名替换tablename。
参考

piok6c0g

piok6c0g2#

这是一个窗口函数问题。对于较旧的mysql版本(<8.0),我们可以使用会话变量来模拟它。请尝试以下操作:

SELECT t1.State, 
       t1.Zip, 
       t1.Areacode, 
       @row_count := CASE 
                       WHEN @ph = t1.Phone Then @row_count + 1
                       ELSE 1 
                     END AS row_count, 
       @ph := t1.Phone AS Phone 
FROM 
  (SELECT State, 
          Zip, 
          Areacode, 
          Phone 
   FROM your_table 
   ORDER BY Phone) AS t1  
CROSS JOIN (SELECT @row_count := 1) AS init1 
CROSS JOIN (SELECT @ph := '') AS init2

ps:op已经确认了 Phone 可以是任何东西。

iovurdzv

iovurdzv3#

如果您是通过电话号码订购,一个简单的解决方案是:

SELECT State, Zip, Areacode, Phone, `Index` FROM (
    SELECT State, 
           Zip, 
           Areacode, 
           Phone, 
           @Idx := IF(@previous_phone=Phone, IFNULL(@Idx,0)+1,1) as Index,
           @previous_phone := Phone
    FROM table 
    ORDER BY Phone
) t;

这只会保持对上一个电话号码的跟踪,并在其更改时重置索引。
如果你想计算的组合zip地区电话重复,然后你可以比较的基础上 CONCAT(Zip,Area,Phone) 例如。

SELECT State, Zip, Areacode, Phone, `Index` FROM (
    SELECT State, 
           Zip, 
           Areacode, 
           Phone, 
           @Idx := IF(@previous_phone=CONCAT(Zip, Area, Phone), IFNULL(@Idx,0)+1,1) as Index, 
           @previous_phone := CONCAT(Zip, Area, Phone)
    FROM table 
    ORDER BY Zip, Area, Phone
) t;

相关问题