简体   繁体   中英

SQL - finding max date

I have some data with 2 date fields: record date and purchase date .

Record date is the first day of every month:

2016-01-01
2016-02-01
2016-03-01 

Purchase date is the date that a product is purchased:

2015-02-14
2016-01-06 

What I need to do is take the most recent purchase date for every record date. So NOT the most recent purchase date overall, which is what MAX(purchasedate) gives me. But the max purchase date BEFORE record date.

So my resulting dataset for the examples I have listed above would be:

Record Date          Most Recent Purchase Date
2016-01-01           2015-02-14
2016-02-01           2016-01-06
2016-03-01           2016-01-06

You can use window function max for find the latest purchase in the order of increasing record_date:

select record_date,
    max(purchase_date) over (
        order by record_date
        ) as latest_purchase_date
from your_table;

You might be able to try this:

select recordDate, max(purchaseDate) from myDB 
 group by recordDate

I am assuming SQL Server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM