简体   繁体   中英

How to filter SQL table relative to a certain datetime?

I'm trying to write a SQL command that would recreate report data from a certain date. The table has three columns (location (varchar), value (int), datetime (datetime)). Over time, rows are added to the table to provide updated values for each location.

What SQL should I be using to: For each location, return only the row with the most recent datetime before a given datetime.

Example:

Location       Value       Datetime

A              5              2011-01-01   
B              6              2011-01-01    
A              7              2012-01-01
A              8              2012-06-01

If I'm curious about 2012-05-01, I would like to get back rows 2 and 3.

What I'm thinking is to GROUP BY location, and specify to keep the largest datetime that is less than the given datetime. I'm assuming there is some built in functionality with datetime objects in SQL that I should be using.

In MySQL 8.x you can use the ROW_NUMBER() window function. For example:

with x as (
  select
    location, value, datetime,
    row_number() over (partition by location order by datetime desc) as rn
  from my_table
  where datetime < '2012-05-01' -- cutoff date
)
select * from x where rn = 1

The straight-forward way: Get the maximum date per location, then select the complete record:

select *
from mytable
where (location, datetime) in
(
  select location, max(datetime)
  from mytable
  where datetime < date '2012-05-01'
  group by location
);

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