基于的删除重复行

时间:2015-08-11 11:10:10

标签: sqlite

我有这样的数据库结构:

CREATE TABLE `tenant_counter` (
    `id`    TEXT,
    `date`  TEXT,
    `time`  TEXT,
    `date_time` TEXT,
    `sayacdeger`    REAL,
    PRIMARY KEY(id,date_time)
);

在某些行中,id,date和sayacdeger会多次出现并保留其值。所以我只需要保留其中一个。我试过了:

delete from tenant_counter 
where exists (
    select 1 from tenant_counter r
    where r.id = tenant_counter.id
    and r.date = tenant_counter.date
    and r.sayacdeger = tenant_counter.sayacdeger
)

但是删除了所有重复的行。

2 个答案:

答案 0 :(得分:1)

您可以使用ROWID,只留下那些对给定数据具有最低(最小)ROWID的行

像这样

delete from tenant_counter 
where exists (
    select 1 from tenant_counter r
    where r.id = tenant_counter.id
    and r.date = tenant_counter.date
    and r.sayacdeger = tenant_counter.sayacdeger
    and r.rowid < tenant_counter.rowid
)

使用IN方法

DELETE FROM tenant_counter 
WHERE ROWID NOT IN ( 
    select min(rowid) from tenant_counter r 
    group by r.id,r.date,r.sayacdeger 
)

答案 1 :(得分:0)

delete   from tenant_counter
where    rowid not in
         (
         select  min(rowid)
         from    tenant_counter AS r
         where r.id = tenant_counter.id
         and r.date = tenant_counter..date
         and r.sayacdeger = tenant_counter.sayacdeger