简体   繁体   English

Oracle SQL 最接近给定日期的日期

[英]Oracle SQL closest date to given date

i have a table with a column for categories, date and price.我有一个表格,其中有一列用于分类、日期和价格。 Like this:像这样:

group 1  - 03.03.2019 - 5.00
group 1  - 03.02.2018 - 4.00
group 2  - 05.05.2019 - 2.25
group 2  - 05.05.2018 - 1.00

So there are (almost) always two dates per group with two different prices.所以(几乎)每组总是有两个日期,两个不同的价格。 Now i need to write an SQL Statement to get the closest date per group to a given date(fe 05.05.2019).现在我需要编写一个 SQL 语句来获取每组最接近给定日期的日期(fe 05.05.2019)。 Group 1 has two dates an the SQL statement needs to Select one of them which is the closest to the given date.组 1 有两个日期,SQL 语句需要选择其中一个最接近给定日期的日期。 This need to happen for all of the groups.所有组都需要这样做。

I tried it for a couple of hours but i am stuck.我试了几个小时,但我被卡住了。 Thanks for ur help谢谢你的帮助

Here is one option using not exists :这是使用not exists一种选择:

select t.*
from mytable t
where not exists (
    select 1
    from mytable t1
    where 
        t1.category = t.category 
        and greatest(t1.date, date '2019-05-05') - least(t1.date, date '2019-05-05')
            < greatest(t.date, date '2019-05-05') - least(t.date, date '2019-05-05')
)

This gives you the "closest" record to 2019-05-05 for each group (whether before or after).这为您提供了每个组(无论是之前还是之后)的“最接近”记录到 2019-05-05。

If, for example, you want the closest record before 2019-05-05, that's a bit simpler:例如,如果您想要 2019-05-05之前最接近的记录那就简单一点:

select t.*
from mytable t
where 
    t.date <= date '2019-05-05'
    and not exists (
        select 1
        from mytable t1
        where t1.category = t.category and t1.date <= date '2019-05-05' and t1.date > t.date
    )

You may be able to use the rank function here您可以在这里使用排名功能

select category, date_value, price from ( 
select category, date_value, price, 
rank() over (partition by category order by 
abs(to_date('2019-05-05','yyyy-mm-dd') - to_date(date_value, 'yyyy-mm-dd')) asc ) rnk
from yourtable )
where rnk = 1

db<>fiddle 数据库<>小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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