TSQL根据最高日期选择不同

twa*_*wal 8 t-sql

我们的数据库有一堆具有相同发票号的记录,但具有不同的日期和不同的注释.

所以你可能有类似的东西

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
Run Code Online (Sandbox Code Playgroud)

我需要选择不同的发票号,日期和备注.用于最近日期的记录.

所以我的结果应该只包含

3622      9/29/1010    Some more notes
4212      10/10/2010   different notes
Run Code Online (Sandbox Code Playgroud)

怎么可能这样做?谢谢!

Vin*_*ard 13

使用分析功能:

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;
Run Code Online (Sandbox Code Playgroud)


Mar*_*tin 9

select invoice, date, notes
from table 
inner join (select invoice, max(date) as date from table group by invoice) as max_date_table      
    on table.invoice = max_date_table.invoice and table.date = max_date_table.date
Run Code Online (Sandbox Code Playgroud)