SQLite)删除(并保留一些)表中的重复项

时间:2015-01-02 11:34:39

标签: sql sqlite join

假设我有一个名为tablex的表,如下所示:

name|year
---------
Bob | 2010
Mary| 2011
Sam | 2012
Mary| 2012
Bob | 2013

名称最多出现两次。我想从表中删除那些重复并且相差一年的名称(在这种情况下,我想保留较新的一年)。

name|year
---------
Bob | 2010
Sam | 2012
Mary| 2012
Bob | 2013

我试过了:

SELECT a.Name, a.Year, b.Year
FROM tablex AS a
LEFT JOIN tablex AS b
ON a.Name=b.Name AND (a.Year=b.Year OR b.Year-a.Year=1)
ORDER BY a.Name, a.Year

结果:

  Name YearA YearB
1  Bob  2010  2010
2  Bob  2013  2013
3 Mary  2011  2011
4 Mary  2011  2012
5 Mary  2012  2012
6  Sam  2012  2012

Bob和Sam的条目是正确的,我如何进一步限制它只包括Mary 2012 2012

4 个答案:

答案 0 :(得分:0)

此操作会从表中删除具有较新年份的相同名称的行:

delete from tablex t1 where year < (select max(year) from tablex where name = t1.name)

答案 1 :(得分:0)

DELETE FROM tablex t
WHERE year + 1 =
  (SELECT MAX(year)
   FROM tablex
   WHERE name = t.name)

或者,如果您不想删除任何内容,但希望查询只提供所需的结果:

SELECT *
FROM tablex t
WHERE year + 1 !=
  (SELECT MAX(year)
   FROM tablex
   WHERE name = t.name)

答案 2 :(得分:0)

从问题不清楚是否要SELECT(抑制重复)或实际删除“重复”。选择案例:

SELECT a.Name, a.Year
FROM tablex AS a
WHERE NOT EXISTS (
    SELECT * FROM tablex AS b
    WHERE b.Name = a.Name
    AND b.Year = a.Year +1
   );

删除案例:

DELETE
FROM tablex AS a
WHERE EXISTS (
    SELECT * FROM tablex AS b
    WHERE b.Name = a.Name
    AND b.Year = a.Year +1
   );

答案 3 :(得分:0)

你可以使用:

SELECT a.Name, a.Year, b.Year
FROM tablex AS a
LEFT JOIN tablex AS b
ON a.Name=b.Name AND (a.Year=b.Year )
ORDER BY a.Name, a.Year