Найти увеличение в истории записей в определенном диапазоне - PullRequest
0 голосов
/ 09 июля 2019

Я хочу найти записи в диапазоне дат 1/1 / 19-1 / 7/19, которые увеличивают сумму

с использованием таблицы HISTORY:

ДАТА СУММЫ ID

(Дата, число, varchar2 (30))

Я нахожу идентификаторы внутри диапазона правильно

при условии, что увеличение / уменьшение может произойти только при наличии двух записей с одинаковым 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
  )

Ответы [ 2 ]

2 голосов
/ 09 июля 2019

Я вижу, что вы нашли решение, но, возможно, вы могли бы сделать это проще, используя 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

0 голосов
/ 09 июля 2019

Добавление объединения последних записей истории перед диапазоном с записями внутри диапазона

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
...