admin

如何计算Oracle SQL中的更改

sql

我有带有以下各列的下表:

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是哈希ID广告,另外4列由group
by语句定义,最后一个列是time_id(该月最后一天的日期)。总的来说,在此表中,我有许多具有许多不同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数据库中执行操作?


阅读 171

收藏
2021-07-01

共1个答案

admin

试试这个:

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
2021-07-01