简体   繁体   English

如何从时间参数中获取最早的日期,而不包括 SQL 中的数据早于时间参数的数据?

[英]How to get earliest date from time parameter without including data that have data older than time parameter in SQL?

I'm struggling for some time with kind of painfull problem.我正在为一种痛苦的问题苦苦挣扎一段时间。

What I want to achieve is to find the blue circle on the image below.我想要实现的是在下图中找到蓝色圆圈。 It is to find date where some name occurs first in the database but it is the furthest date out of all possible occurences (furthest in terms of distance between start date parameter and all possible gaps between start date and data)它是查找某个name在数据库中首先出现的date ,但它是所有可能出现的最远日期(就start date parameter和开始日期和数据之间所有可能的差距而言,距离最远)

I know how to find the date right after start date.我知道如何在开始日期之后找到日期。 To do this I'm using that query.为此,我正在使用该查询。

SELECT *
FROM animals
WHERE date(date) > '2020-01-01'
ORDER BY date ASC
LIMIT 1 ;

But I don't know how to exclude the data that occurs before 2020-01-01 in this query.但我不知道如何在此查询中排除2020-01-01之前发生的数据。

I would like to do it in form of SQL query.我想以 SQL 查询的形式进行。

帮助图片

My SQL table looks like this:我的 SQL 表如下所示:

date日期 name姓名 value价值
2022-02-01 2022-02-01 dog 45.5 45.5
2022-02-01 2022-02-01 cat 2.5 2.5
2022-02-01 2022-02-01 snake 2.5 2.5
2022-01-31 2022-01-31 dog 42.5 42.5
2022-01-31 2022-01-31 cat 3.4 3.4
2022-01-31 2022-01-31 snake 43.2 43.2
2022-01-30 2022-01-30 dog 43.2 43.2
2022-01-30 2022-01-30 cat 43.2 43.2
2022-01-30 2022-01-30 snake 43.2 43.2
2022-01-29 2022-01-29 dog 43.2 43.2
2022-01-29 2022-01-29 snake 43.2 43.2
2022-01-28 2022-01-28 dog 43.2 43.2

And let's say that I'm looking for date after 2022-01-28 .假设我正在寻找2022-01-28之后的日期。 Now gap between start_date and first occurence of dog is 0 because dog has data for 2022-01-28 .现在start_date和 dog 的第一次出现之间的差距是 0 因为 dog 有2022-01-28的数据。 For snake it is 1 day ( 2022-01-29 ) and for cat it's 2 ( 2022-01-30 )蛇是 1 天( 2022-01-29 ),猫是 2 天( 2022-01-30

So my result should be 2022-01-30 (2 days from start_date for cat) because it is the furthest from the start_date所以我的结果应该是 2022-01-30(对于 cat 来说是 start_date 2 天),因为它离start_date最远

Search for distinct on and you'll see several explanations on how to solve this.搜索distinct on ,你会看到一些关于如何解决这个问题的解释。

This should work (I changed date field to event_date to keep it less confusing)这应该有效(我将日期字段更改为 event_date 以减少混乱)

with earliest_dates as (
 select distinct on (name) name, event_date 
 from animals
 where event_date > '2020-01-01'
 order by name, event_date
)
select  max(event_date) - min(event_date) as days
from earliest_dates;

sql fiddle link for test setup http://sqlfiddle.com/#!15/67389/4/0 sql 用于测试设置的小提琴链接http://sqlfiddle.com/#!15/67389/4/0

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

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