简体   繁体   中英

How to pull most recent date in the past in SQL

I am looking for a sql query that display the most current date in the past. For example I have the following columns:

CLIENT          DATE
1234567890      2017-01-01
1234567890      2018-05-17
1234567890      2018-05-18
1234567890      2018-09-18

Desired output:

6173282305      2018-05-18

I have tried combinations of getdate() and MAX() to no avail. Any help would be appreciated. Thanks all.

You can use order by and fetch first :

select t.*
from t
where t.date < current_date
order by t.date desc
fetch first 1 row only;

This is basically ANSI-standard syntax. Some databases prefer limit or top to fetch first . Some prefer getdate() or sysdate or something else for the current date. But the logic is the same, even if the syntax varies a bit.

select max(date) from t group by client having max(date) < getdate()

You could use a windows function and a cte like this:

With cte as (Select client, Date, Row_number() over (partition by client order by date desc) as date_count From [tableName])

Select * from cte Where date_count = 1

That row_number syntax might be a bit off, but should give you an idea.

You didn't specify SQL dialect. Here are a couple of methods one might use with SQL Server.

Method A

First, choose the two most recent records, and from those, choose the oldest record:

/* from the two most recent records, choose the oldest */
SELECT TOP 1
  [Client], [Date]
FROM (
      /* choose the two most recent records */
      SELECT TOP 2
        [Client], [Date]
      FROM [TableName]
      ORDER BY [Date] DESC) x
ORDER BY [Date] ASC

Link to SQL Fiddle: http://sqlfiddle.com/#!18/38054/2

Method B

Find the largest date value and specify a filter to select all records with dates less than that. From that group select the most recent date:

SELECT TOP 1
  [Client], [Date]
FROM [TableName]
WHERE [Date] < (SELECT MAX([Date]) FROM [TableName])
ORDER BY [Date] Desc

Link to SQL Fiddle: http://sqlfiddle.com/#!18/38054/6

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