如何计算 Oracle 中的变化 sql

How to calculate changes in Oracle sql

我有以下 table 以下列:

HID_1 HID_2 Attr1 Attr2 Attr3 Attr4  Attr5    
123   111    wo     e    ak    ERR   20180630    
123   111    wo     e    ak    ERR   20180730     
123   111    wo     e    ak    ERR   20180830     
123   111    qe     e    ak    ERR   20180930    
123   111    qe     e    ak    ERR   20181030    
123   111    aa     a    ak    ERR   20181130

其中HID_1和HID_2为hash-id,其他4列由group by语句定义,最后一列为time_id(date of the last day of the last day月)。总的来说,在这个 table 我有更多的记录,有很多不同的 HID。

我想将 HID_2 的一些更改(在 Attr1 - Attr4 中)计算为单独的列。 根据第一个例子,答案应该是这样的:

HID_1 HID_2 Attr1 Attr2 Attr3 Attr4  Attr5     Attr6    
123   111    wo     e    ak    ERR   20180630   0    
123   111    wo     e    ak    ERR   20180730   0    
123   111    wo     e    ak    ERR   20180830   0    
123   111    qe     e    ak    ERR   20180930   1     
123   111    qe     e    ak    ERR   20181030   0    
123   111    aa     a    ak    ERR   20181130   2

如何在 Oracle sql 数据库中执行操作?

我想你想要:

select t.*,
       dense_rank() over (partition by hid_1, hid_2 order by min_attr5) as attr6
from (select t.*,
             min(attr5) over (partition by hid_1, hid_2, , attr1, attr2, attr3, attr4, seqnum_2 - seqnum) as min_attr5
      from (select t.*,
                   row_number() over (partition by hid_1, hid_2 order by attr5) as seqnum,
                   row_number() over (partition by hid_1, hid_2, attr1, attr2, attr3, attr4 order by attr5) as seqnum_2
            from t
      ) t;

试试这个:

select t.* 
, case when attr1 != LAG(attr1, 1, attr1) OVER (PARTITION BY hid_1, hid_2 ORDER BY attr5) then 1 else 0 end +
  case when attr2 != LAG(attr2, 1, attr2) OVER (PARTITION BY hid_1, hid_2 ORDER BY attr5) then 1 else 0 end +
  case when attr3 != LAG(attr3, 1, attr3) OVER (PARTITION BY hid_1, hid_2 ORDER BY attr5) then 1 else 0 end +
  case when attr4 != LAG(attr4, 1, attr4) OVER (PARTITION BY hid_1, hid_2 ORDER BY attr5) then 1 else 0 end as attr6
from t