开发者

SQLite: Delete duplicate entries

开发者 https://www.devze.com 2023-03-08 07:25 出处:网络
I am new to SQLite and I would like to find a solution to deleting duplicate entries based on a certain condition.

I am new to SQLite and I would like to find a solution to deleting duplicate entries based on a certain condition. Suppose I have a table like this:

ID | Person1 | ID1 | Person2 | ID2 | Average
-------------------------------------------
1  | Name1   |   1  | Name4 |   4  | 47
2  | Name1   |   1  | Name5 |   5  | 88
3  | Name1   |   1  | Name6 |   6  | 15
----------------------------------------
4  | Name2   |   2  | Name4 |   4  | 90
5  | Name2   |   2  | Name5 |   5  | 80
6  | Name2   |   2  | Name6 |   6  | 45
----------------------------------------
7  | Name3   |   3  | Name4 |   4  | 30
8  | Name3   |   3  | Name5 |   5  | 20
开发者_开发百科9  | Name3   |   3  | Name6 |   6  | 79

and want a table like this:

ID | Person1 | ID1 | Person2 | ID2  | Average
-------------------------------------------
2  | Name1   |   1  | Name5 |   5   | 88
5  | Name2   |   2  | Name4 |   4   | 90
9  | Name3   |   3  | Name6 |   6   | 79

Is there anyway of doing this? Thanks in advance.


This works:

DELETE FROM tablename
WHERE ID NOT IN (
    SELECT T.ID
    FROM (
        SELECT ID1, MAX(Average) AS MAverage
        FROM TableName
        GROUP BY ID1
    ) AS X
    INNER JOIN TableName T
        ON X.ID1 = T.ID1 AND X.MAverage = T.Average
);

This query finds the rows with the highest average per person (based on ID1), then deletes all the other rows.

0

精彩评论

暂无评论...
验证码 换一张
取 消