简体   繁体   English

在 SQL 中查找组级别第一次出现的日期

[英]Find date of first occurrence at the group level in SQL

I'm looking to build a query that retrieves the date field for the first time a particular occurrence is recorded, at the ID level.我希望构建一个查询,以在 ID 级别首次记录特定事件时检索日期字段。 Below's 'FIRST_DATE' field is what I'm trying to achieve.下面的“FIRST_DATE”字段是我想要实现的。

In this example, October 2020 is the first date that ID_FIELD 1 has a non-zero value, so Oct 2020 is applied as the FIRST_DATE for all ID_FIELD 1 rows.在此示例中,2020 年 10 月是 ID_FIELD 1 具有非零值的第一个日期,因此 2020 年 10 月作为所有 ID_FIELD 1 行的 FIRST_DATE 应用。 The intention is to be able to calculate the amount of time passed since an ID's value has changed from 0 to 1. Using Oracle SQL Developer.目的是能够计算自 ID 值从 0 变为 1 以来经过的时间量。使用 Oracle SQL Developer。

ID_FIELD ID_FIELD DATE_FIELD DATE_FIELD VALUE价值 FIRST_DATE第一次约会
1 1 01-JUL-20 20 年 7 月 1 日 0 0 01-OCT-20 01-OCT-20
1 1 01-AUG-20 20 年 8 月 1 日 0 0 01-OCT-20 01-OCT-20
1 1 01-SEP-20 01-SEP-20 0 0 01-OCT-20 01-OCT-20
1 1 01-OCT-20 01-OCT-20 1 1 01-OCT-20 01-OCT-20
1 1 01-NOV-20 20 年 11 月 1 日 1 1 01-OCT-20 01-OCT-20
1 1 01-DEC-20 20 年 12 月 1 日 1 1 01-OCT-20 01-OCT-20
2 2 01-JUL-20 20 年 7 月 1 日 0 0 01-AUG-20 20 年 8 月 1 日
2 2 01-AUG-20 20 年 8 月 1 日 1 1 01-AUG-20 20 年 8 月 1 日
2 2 01-SEP-20 01-SEP-20 1 1 01-AUG-20 20 年 8 月 1 日

Thank you!谢谢!

You can use the analytic version of min , combined with a case expression:您可以使用min的分析版本,并结合 case 表达式:

select id_field, date_field, value,
  min(case when value != 0 then date_field end) over (partition by id_field) as first_date
from your_table;

db<>fiddle , including a couple of versions that calculates the elapsed days, depending on eactly what you want to do. db<>fiddle ,包括几个计算经过天数的版本,具体取决于您想要做什么。

SELECT id_field, MIN(DECODE(VALUE, 0, NULL, DATE_FIELD))
FROM table_name
GROUP BY id_field

You can then use that as part of your update statement.然后,您可以将其用作更新语句的一部分。

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

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