Skip to content
Advertisement

MySQL find first row base on multiple conditions

Suppose exists a table as follows:

For each id, i want to keep the row with maximum B, if B equals, then keep the row with maximum C. So the final result is,

how to realize it by SQL?

Advertisement

Answer

Maximum tasks can be solved with NOT EXISTS. You only want rows for which not exists a row with the same ID and a greater B or the same B and a higher C.

As of MyQL 8 we can simply rank our rows with RANK, DENSE_RANK or ROW_NUMBER instead:

Demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=a54a906373e0dd00a2fb42c119186dd3

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement