How to calculate changes in Oracle sql

流过昼夜 提交于 2019-12-11 06:49:51

问题


I have the following table with the following columns:

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

Where HID_1 and HID_2 are hash-id ad other 4 columns are defined by the group by statement and the last one is time_id(date of the last day of the month). In general in this table I have much more records with a lot of different HID.

I want to coumpute a number of changes(in Attr1 - Attr4) for the HID_2 as separate column. Based on the first example the answer should be like this:

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

How can I do in Oracle sql Database?


回答1:


Try this:

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



回答2:


I think you want:

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;


来源:https://stackoverflow.com/questions/54748975/how-to-calculate-changes-in-oracle-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!