Janka Alex
Janka Alex

Reputation: 13

How to "filter" records in Hive table?

Imagine table with id, status and modified_date. One id can have more than one record in table. I need to get out only that row for each id that has current status together with the modified_date when this status has changed from older one to current.

id            status          modified_date,
--------------------------------------------
1               T             1-Jan,
1               T             2-Jan,
1               F             3-Jan,
1               F             4-Jan,
1               T             5-Jan,
1               T             6-Jan,
2               F             18-Feb,
2               F             20-Feb,
2               T             21-Feb,
3               F             1-Mar,
3               F             1-Mar,
3               F             2-Mar,

With everything I already did I can not capture the second change for person 1 from F to T on 5-Jan.

So I expect results :

id            status          modified_date,
--------------------------------------------
1               T             5-Jan,
2               T             21-Feb,
3               F             1-Mar,

Upvotes: 1

Views: 250

Answers (1)

leftjoin
leftjoin

Reputation: 38325

Using lag() analytic function you can address previous row to calculate status_changed flag. Then use row_number to mark last status changed rows with 1 and filter them. See comments in the code:

with your_data as (--replace with your table
select stack(12,
1,'T','1-Jan',
1,'T','2-Jan',
1,'F','3-Jan',
1,'F','4-Jan',
1,'T','5-Jan',
1,'T','6-Jan',
2,'F','18-Feb',
2,'F','20-Feb',
2,'T','21-Feb',
3,'F','1-Mar',
3,'F','1-Mar',
3,'F','2-Mar') as (id,status,modified_date)
)
select id,status,modified_date
from
(
select id,status,modified_date,status_changed_flag,
       row_number() over(partition by id, status_changed_flag order by modified_date desc) rn  
 from 
(
select t.*, 
       --lag(status) over(partition by id order by modified_date) prev_status,
       NVL((lag(status) over(partition by id order by modified_date)!=status), true) status_changed_flag
  from your_data t
)s
)s where status_changed_flag and rn=1
order by id --remove ordering if not necessary
;

Result:

OK
id   status   modified_date
1       T       5-Jan
2       T       21-Feb
3       F       1-Mar
Time taken: 178.643 seconds, Fetched: 3 row(s)

Upvotes: 1

Related Questions