Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Filter rows with max value

This is my table structure:

File    |   Version     |   Function
1       |   1           |   1
1       |   2           |   1
1       |   3           |   1
1       |   2           |   2

2       |   1           |   4
3       |   2           |   5

I need it to return these rows only

1       |   3           |   1
2       |   1           |   4
3       |   2           |   5

Meaning I only want the functions that have the most recent version for each file.

I do not want the result below, i.e unique function ids that are not the most recent version

1       |   3           |   1
1       |   2           |   2
...

I've looked at How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?, but that returns the most recent unique function ids.

The query needs to be sqlite3 compatible.

like image 206
danihodovic Avatar asked Jul 11 '14 23:07

danihodovic


People also ask

How do I select the maximum row value in SQL?

We used the MAX() function within a subquery to find the maximum value, and returned the whole row with the outer query.

How do I get the maximum value from another column of a table in SQL?

In SQL Server there are several ways to get the MIN or MAX of multiple columns including methods using UNPIVOT, UNION, CASE, etc… However, the simplest method is by using FROM … VALUES i.e. table value constructor. Let's see an example. In this example, there is a table for items with five columns for prices.

How do I select 3 max values in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.


2 Answers

An efficient way to do this is often to use not exists:

select t.*
from table t
where not exists (select 1
                  from table t2
                  where t2.file = t.file and t2.Version > t.version
                 );

This query can take advantage of an index on table(file, version).

This rephrases the query to be: "Get me all rows from the table where the corresponding file has no larger version."

like image 111
Gordon Linoff Avatar answered Sep 23 '22 06:09

Gordon Linoff


In SQLite 3.7.11 or later, when you use MAX, the other values are guaranteed to come from the row with the largest value:

SELECT File,
       MAX(Version) AS Version,
       Function
FROM MyTable
GROUP BY File
like image 27
CL. Avatar answered Sep 24 '22 06:09

CL.