Reputation: 437
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?
Upvotes: 1
Views: 112
Reputation: 1612
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
Upvotes: 3
Reputation: 1270091
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;
Upvotes: 2