TSQL根据最高日期选择不同

时间:2010-10-26 16:55:04

标签: tsql

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

所以你可能会有像

这样的东西
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

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

所以我的结果应该只包含

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

怎么可能这样做? 谢谢!

3 个答案:

答案 0 :(得分:12)

使用分析功能:

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;

答案 1 :(得分: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

答案 2 :(得分:1)

尝试:

SELECT I.* 
FROM MyInvoice AS I
INNER JOIN 
           (SELECT Invoice, MAX([Date]) AS MaxDate
            FROM MyInvoice 
            GROUP BY Invoice
           ) AS M ON I.Date = M.MaxDate 
                 AND I.Invoice = M.Invoice