简体   繁体   中英

sqlite delete rows group by having more than two rows

I have following table structure:

sqlite> select * from test;      
k1          k2          value     
----------  ----------  ----------
1           1           10        
1           1           20
1           1           30        
1           2           10

Here, I want to delete rows grouped on (k1,k2) having more than two rows.

So, I want to delete first three rows (1,1,10), (1,1,20) and (1,1,30).

I tried following:

delete from test where rowid in (select test.rowid from test group by k1,k2 having count(*) > 2);

But, the subquery gives only the last rowid:

sqlite> select test.rowid from test group by k1,k2 having count(*) > 2;
rowid     
----------
3

Hence, all three rows are not getting deleted. And, I cannot directly use group by in delete query.

Any idea on, how it can be achieved via query?

You can use exists :

delete from test
    where exists (select 1
                  from test t2
                  where t2.k1 = test.k1 and t2.k2 = test.k2
                  group by t2.k1, t2.k2
                  having count(*) > 2
                 );

Or use in with tuples:

delete from test
    where (k1, k2) in (select t2.k1, t2.k2
                       from test t2
                       group by t2.k1, t2.k2
                       having count(*) > 2
                      );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM