Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL selecting distinct based on the highest date

Tags:

tsql

Our database has a bunch of records that have the same invoice number, but have different dates and different notes.

so you might have something like

invoice    date         notes
 3622      1/3/2010     some notes
 3622      9/12/2010    some different notes
 3622      9/29/1010    Some more notes
 4212      9/1/2009     notes
 4212      10/10/2010   different notes

I need to select the distinct invoice numbers, dates and notes. for the record with the most recent date.

so my result should contain just

3622      9/29/1010    Some more notes
4212      10/10/2010   different notes

how is it possible to do this? Thanks!

like image 662
twal Avatar asked Oct 26 '10 16:10

twal


1 Answers

Use analytical functions :

WITH TT AS (
    SELECT invoice, date, notes, RANK() OVER(PARTITION BY invoice ORDER BY date DESC) AS R
    FROM table
)
SELECT invoice, date, notes
FROM TT
WHERE R = 1;
like image 52
Vincent Savard Avatar answered Oct 21 '22 08:10

Vincent Savard