3

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          
4

2 回答 2

5

尝试这个:

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;

或“不太复杂”的版本(不使用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;
于 2013-07-20T17:47:44.213 回答
1

尝试这个?这仅在每个 vim 有一个 Datechange 时才有效。如果您有多个,则需要进行更改

Select tbl_veh.vin, tbl_veh.record
From tbl_veh
Inner join (select vin, max(Datechange) 
            from tbl_veh
             group by vin
            ) last 
     On last.vin = tbl_veh.vin
于 2013-07-20T17:45:40.970 回答