【问题标题】:Find increase in history records in specific range查找特定范围内历史记录的增加
【发布时间】:2019-07-09 10:03:28
【问题描述】:

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

使用表HISTORY:

日期金额 ID

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

我正确地找到了范围内的 ID

假设只有当有两个具有相同 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
  )

【问题讨论】:

    标签: sql oracle date-range


    【解决方案1】:

    我看到你找到了解决方案,但也许你可以更简单地使用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

    【讨论】:

    • 谢谢,我会检查一下,使用分析函数(作为滞后)总是对性能不利吗?
    • @user7294900 。 . .分析函数的性能通常优于替代函数。
    【解决方案2】:

    添加范围前的最后历史记录与范围内的记录的联合

    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
    

    【讨论】:

      猜你喜欢
      • 2017-12-02
      • 2018-11-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2022-01-06
      相关资源
      最近更新 更多