使用sqlite查找连续的重复数

时间:2016-02-01 10:11:55

标签: sqlite

我有一个数据库表,其中包含与每个条目名称相关联的8个数字的条目。因此,我需要编写一个查询来获取联系人姓名的总数,这些联系人姓名与每个联系人姓名相关联。 我有一个sqlite表,如下图所示

  

姓名| Num0 | Num1 | Num2 | Num3 | Num4 | Num5 | Num6 | Num7

假设我有6000个条目,并且有100个条目具有重复的数字,这些条目可以属于从TelNum0到TelNum8的任何列。

例如:如下所示,我有一个数据库,共有5个条目,总共有5个名称,如:

Name       Num0    Num1    Num2   Num3   Num4  Num5   Num6  Num7  
1)John     1234    1234    1234 

2)Hebbar   234   

3)Jim      9876    9876    9876

4)Kim      111     111     111

5)Kate     666

现在,当我运行查询时,我应该将结果数量设为3,因为John,Jim和Kim有与之关联的重复条目。

提前多多感谢

1 个答案:

答案 0 :(得分:2)

首先,正确地规范化数据:

SELECT Name, Num0 AS Num FROM MyTable WHERE Num0 IS NOT NULL
UNION ALL
SELECT Name, Num1        FROM MyTable WHERE Num1 IS NOT NULL
UNION ALL
SELECT Name, Num2        FROM MyTable WHERE Num2 IS NOT NULL
UNION ALL
SELECT Name, Num3        FROM MyTable WHERE Num3 IS NOT NULL
UNION ALL
SELECT Name, Num4        FROM MyTable WHERE Num4 IS NOT NULL
UNION ALL
SELECT Name, Num5        FROM MyTable WHERE Num5 IS NOT NULL
UNION ALL
SELECT Name, Num6        FROM MyTable WHERE Num6 IS NOT NULL
UNION ALL
SELECT Name, Num7        FROM MyTable WHERE Num7 IS NOT NULL;
Name   Num
------ ----
John   1234
John   1234
John   1234
Hebbar 234
Jim    9876
Jim    9876
Jim    9876
Kim    111
Kim    111
Kim    111
Kate   666

然后只计算重复项:

SELECT Name, Num, COUNT(*)
FROM (SELECT Name, Num0 AS Num FROM MyTable WHERE Num0 IS NOT NULL
      UNION ALL
      SELECT Name, Num1        FROM MyTable WHERE Num1 IS NOT NULL
      UNION ALL
      SELECT Name, Num2        FROM MyTable WHERE Num2 IS NOT NULL
      UNION ALL
      SELECT Name, Num3        FROM MyTable WHERE Num3 IS NOT NULL
      UNION ALL
      SELECT Name, Num4        FROM MyTable WHERE Num4 IS NOT NULL
      UNION ALL
      SELECT Name, Num5        FROM MyTable WHERE Num5 IS NOT NULL
      UNION ALL
      SELECT Name, Num6        FROM MyTable WHERE Num6 IS NOT NULL
      UNION ALL
      SELECT Name, Num7        FROM MyTable WHERE Num7 IS NOT NULL)
GROUP BY Name, Num
HAVING COUNT(*) > 1;