我有一个表,该表在一定时间后会获得陈旧(相似)值。我想找到最后一个连续值的计数。您能帮我为此编写一个Oracle SQL查询吗?我已经在下面打印了示例输入和输出。
输入:
ID date value
2641 02/01/2019 5.6
2641 02/04/2019 5.7
2641 02/05/2019 6.2
2641 02/06/2019 6.2
2641 02/07/2019 4.3
2641 02/08/2019 4.3
2641 02/11/2019 4.3
2641 02/12/2019 4.3
2641 02/13/2019 4.3
2641 02/14/2019 4.3
2641 02/15/2019 4.3
2641 02/18/2019 4.3
2641 02/19/2019 4.3
2642 02/01/2019 7.6
2642 02/04/2019 4.7
2642 02/05/2019 5.2
2642 02/06/2019 3.8
2642 02/07/2019 3.8
2642 02/08/2019 3.8
2642 02/11/2019 3.8
2642 02/12/2019 3.8
2642 02/13/2019 3.8
2642 02/14/2019 3.8
2642 02/15/2019 3.8
2642 02/18/2019 3.8
2642 02/19/2019 3.8
输出
ID stale_days
2641 9
2642 10
关于, 沙旺
答案 0 :(得分:1)
我会那样做。
想法是让每一行都获得后面所有行的最大值和后面所有行的最小值。如果该值与最小值和最大值相同,则将它们计数。
SELECT ID, COUNT(*) FROM (
SELECT
ID,
VALUE,
MIN(VALUE) OVER ( PARTITION BY ID ORDER BY D ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING ) AS MIN_NEXT,
MAX(VALUE) OVER ( PARTITION BY ID ORDER BY D ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING ) AS MAX_NEXT
FROM T
) WHERE VALUE=MIN_NEXT AND VALUE=MAX_NEXT
GROUP BY ID;
答案 1 :(得分:0)
with rows_with_cons_val as
(
select t.*, rowid, row_number() over (partition by id, value order by date_entered)
rid
from t)
select id, rid as stale_days
from (
select r.*, max(date_entered) over (partition by id) as selection
from rows_with_cons_val r) where date_entered = selection;