简体   繁体   中英

SQL Server, get most recent record within a specified date range

I'm trying to figure out how to do this via a view if possible (definitely aware this can be done in-line, via a function, and/or a proc.

There's a view that needs to dedupe a dataset and pick the most recent record. So I'm trying to use wither row_number(), or even a top 1 order by via a cross apply, but the problem is that the query can filter on a date, so for eg.

select x
from view
where date < somedate

and the most recent record needs to be calculated for that filtered dataset. Is there a way to do this in a view? a correlated subquery comes to mind but try as I may, either I get the full duped dataset, or it picks the most recent on the table without a date filter, then applies the date filter after the fact, which isn't the same thing.

Some background per Yogesh: The table in question contains history of an employee table, where each employee_id can exist multiple times with different date values. There is a primary key on this table which is an employeehistory_id (identity). The goal is to get the most recent record for all employees (1 unique record per employee) where the date < some date. The problem with the windowing is that it needs to almost have the date filter in a subquery within the view (from what I'm seeing). Hopefully that helps clarify the answer.

Currently the view would be something like

    SELECT a.*
    FROM employeehistory a
    join (select employee_id, employeehistory_ID, row_number()OVER(PARTITION 
                 BY employee_id ORDER BY Date DESC) as Ranked
          FROM employeehistory) b
      on a.employee_id = b.employee_id
      and a.employeehistory_ID = b.employeehistory_ID
    where b.Ranked = 1

so as you can see, filtering the view with a date, doesn't propagate necessarily to the inner. So asking to see if there is a way to still keep this functional in a view. Once again, I'm aware this can be done either as a function or a proc. Thanks!

We're using SQL Server 2016 Enterprise edition.

how about

select top 1 x
from view
where date < somedate
order by date desc
SELECT TOP 1 x
FROM [View]
WHERE 
    date < somedate
ORDER BY 
    date DESC
select *
from MyView
where myDate < somedate
order by myDate desc
limit 1;

limit 1 is the same as top 1 but for MySQL. I have a fiddle that shows what I think your expected output should look like for it as well. http://sqlfiddle.com/#!9/209226/7

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