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

SQL(ite) Remove (and keep some) duplicates in table

假设我有一个table,叫做tablex,如下:

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

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

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

此操作从 table 中删除行,其中还存在具有较新年份的相同名称:

delete from tablex t1 where year < (select max(year) from tablex where name = t1.name)
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)

问题不清楚你是想SELECT(抑制重复项)还是实际删除"duplicates"。 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
   );

您可以使用:

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