查找特定范围内历史记录的增加

Find increase in history records in specific range

我想在日期范围 1/1/19-1/7/19 中查找增加金额的记录

使用 table HISTORY:

DATE AMOUNT ID

(日期、数字、varchar2(30))

我正确找到范围内的 ID

假设 increase/decrease 只有在有两个具有相同 ID 的记录时才会发生

 with suspect as
 (select id
    from history
   where t.createddate < to_date('2019-07-01', 'yyyy-mm-dd')
   group by id
  having count(1) > 1),
ids as
 (select id
    from history
    join suspect
      on history.id = suspect.id
   where history.date > to_date('2019-01-01', 'yyyy-mm-dd')
     and history.date < to_date('2019-07-01', 'yyyy-mm-dd'))
select count(distinct id)
  from history a, history b
 where a.id = b.id
   and a.date < b.date
   and a.amount < b.amount

寻找增加的问题我需要找到以前的记录,它可以在时间范围

之前

我可以找到时间范围之前的最后一次,但我没有使用它:

ids_prevtime as (
  select history.*, max(t.date) over (partition by t.id) max_date
  from history   
  join ids on history.userid = ids.id
   where history.date < to_date('2019-01-01','yyyy-mm-dd' )  
  ), ids_prev as (
  select * from ids_prevtime where createdate=max_date
  )

添加范围前最后历史记录与范围内记录的并集

ids_prev as
 (select ID, DATE, AMOUNT
    from id_before_rangetime
   where createddate = max_date),
ids_in_range as
 (select history.*
    from history
    join ids
      on history.ID = ids.ID
   where history.date > to_date('2019-01-01', 'yyyy-mm-dd')
     and history.date < to_date('2019-07-01', 'yyyy-mm-dd')),
all_relevant as
 (select * from ids_in_range union all select * from ids_prev)

然后计数增加:

select count(distinct id)
  from all_relevant a, all_relevant b
 where a.id = b.id
   and a.date < b.date
   and a.amount < b.amount

我看到您找到了解决方案,但也许您可以更简单地使用 lag():

select count(distinct id)
  from (select id, date_, amount, 
               lag(amount) over (partition by id order by date_) prev_amt
          from history)
  where date_ between date '2019-01-01' and date '2019-07-01' 
    and amount > prev_amt;

dbfiddle