【问题标题】:How to index rows with duplicate values in a column?如何索引列中具有重复值的行?
【发布时间】:2019-03-15 07:23:23
【问题描述】:

如何计算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

【问题讨论】:

  • 你的 MySQL 版本是多少?
  • 所以你想有行索引,而不是有多少相同的项目?
  • @MadhurBhaiya 我有 SQLyog Ultimate 的 SQL 版本 - MySQL GUI 8.5
  • 如何在 phone 的“分区”中定义 row_count ?对于同一电话号码,哪一行的 row_count = 1 ?
  • @Gowtham 那部分很清楚。但是你如何决定哪一行给 1,哪一行 2 等等..

标签: mysql count duplicates


【解决方案1】:

这是一个Window function 问题。对于较旧的 MySQL 版本 (),我们可以使用 Session variables 模拟它。请尝试以下操作:

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 有confirmedPhone 分区内的编号可以是任何东西。

【讨论】:

  • @Gowtham 乐于提供帮助 :) 我希望您能从查询中弄清楚它在做什么以及如何做!如果需要解释,请告诉我。阅读本文以获得想法:mysqltutorial.org/mysql-row_number
【解决方案2】:

下面是 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;

将 TableName 替换为您的 Mysql 表名。

Reference

【讨论】:

  • 此查询不返回 OP 要求的内容。由于您是按除 3 列之外的所有列进行分组(并且没有行在这 3 列中重复),因此不会返回任何行。
【解决方案3】:

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

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 Area Phone 组合的重复次数,则可以根据 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;

【讨论】:

    猜你喜欢
    • 2019-07-14
    • 2017-12-01
    • 1970-01-01
    • 2021-12-08
    • 2022-01-11
    • 1970-01-01
    • 2013-02-18
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多