简体   繁体   中英

From every set of rows with the same value in column A delete all rows but the row with the highest value in column B

I'm searching for a SQL command that does the following:

From every set of rows with the same value in column A delete all rows but the row with the highest value in column B. If there are multiple rows with the same B value in a set keep at least one of them.

Additional notes

  • The column format should not be modified nor additional tables should be required to achieve the desired result.
  • The table has only two columns from which none is primary, unique or multiple occurrences key.
  • The query should work well with bigger datasets ie the running time should be proportional to the number of rows in the table (not quadratic/exponential).

Example:

Initial state:

+---+---+
| A | B |
+---+---+
| x | 1 |
| x | 2 |
| y | 3 |
+---+---+

Desired result:

+---+---+
| A | B |
+---+---+
| x | 2 |
| y | 3 |
+---+---+

Oy, this is a pain. I think the best way is truncate / insert :

create table temp_t as
    select *
    from t;

truncate table t;

insert into t(a, b)
    select distinct a, b
    from temp_t tt
    where tt.b = (select max(tt2.b) from temp_t tt2 where tt2.a = tt.a);

Another alternative would be to add a third column and assign that a unique number, which can then be used for the delete.

This query should work!!

I am retaining all the MAX B's for each A and deleting all the remaining rows from the table which are not required.

DELETE s1
FROM table s1,
    ( SELECT A,MAX(B) AS B FROM table GROUP BY A ) s2
WHERE s1.A = s2.A 
    AND s1.B <> s2.B;

Use MySQL's multi-table delete:

delete t2
from mytable t1, mytable t2
where t2.A = t1.A
and t2.B < t1.B

An index on column A will make this perform well.

Use a JOIN with a subquery that gets the maximum B for each A, and make the JOIN condition match the rows where B doesn't match this.

DELETE t1
FROM Table AS t1
JOIN (
    SELECT A, MAX(B) AS maxB
    FROM Table
    GROUP BY A) AS t2
ON t1.A = t2.A AND t1.B != maxB

To get rid of the duplicates that remain, use one of the solutions in How to delete duplicates on a MySQL table?

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