Possible Duplicate:
How do you select only the maximum version of a list of documents that have different versions in SQL?
I have a table of that stores versions of files and the page those files are associated with
CREATE TABLE tbl (id int, title varchar(32), version int, pageid int);
insert into tbl values (1, 'file1', 1, 25);
insert into tbl values (2, 'file2', 1, 25);
insert into tbl values (3, 'file1', 2, 25);
insert into tbl values (4, 'file2', 2, 25);
insert into tbl values (5, 'file3', 1, 25);
insert into tbl values (6, 'file1', 1, 24);
insert into tbl values (7, 'file2', 1, 24);
insert into tbl values (8, 'file1', 2, 24);
insert into tbl values (9, 'file2', 2, 24);
insert into tbl values (10, 'file3', 1, 24);
I would like to generate a query that returns to me only the maximum versions of documents that are attached to pageid=25, not pageid=24. Running the query should yield only rows 3,4,5 and not rows 8,9,10 (because they are associated with pageid=24).
I have put together a SQL Fiddle for this problem.
Here’s a simple query which does the trick:
And here’s its SQL Fiddle output — does it do what you’re looking for?