Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subqueries / join on the same table

I have a table that looks like the following

Table tbl_veh

VIN         Record    DateChange
11223344      123A    6/24/2012
11223344      121G    7/20/2013
11223344      2D54    2/24/2013
55445588      44D4    2/27/2012
55445588      855D    3/15/2013

So I would like to select the VIN and record but only for the most recent date. How would I do that?

So I would get back

11223344 and 121G
55445588 and 855D          
like image 396
Tony Larson Avatar asked Aug 12 '26 07:08

Tony Larson


1 Answers

Try this:

WITH [ranked] AS (
     SELECT VIN, Record, RANK() OVER(PARTITION BY VIN ORDER BY DateChange DESC, newid()) [rank]
     FROM tbl_veh)

SELECT VIN, Record
FROM [ranked]
WHERE [rank] = 1;

or "less complex" version (without using CTE):

SELECT VIN, Record
FROM (
    SELECT VIN, Record, RANK() OVER(PARTITION BY VIN ORDER BY DateChange DESC, newid()) [rank]
    FROM tbl_veh) as [ranked] 
WHERE [rank] = 1;
like image 53
Andrey Morozov Avatar answered Aug 15 '26 03:08

Andrey Morozov