简体   繁体   中英

Select from a table and bind correctly on the columns DB2/Oracle

I have a scenario where I have to select rows from a table and given the requirements, I cannot come up with a sql statement where it could retrieve the rows correctly.

ID  EFFDT        STATUS
1   2001-01-01   A
1   2002-01-01   A
1   2003-01-01   B
1   2004-01-01   B
1   2005-01-01   A
1   2006-01-01   B

I would like to grab all the rows which were not changed at the point of time and get their mininum effective date.

I tried something like:

Select e.* 
from employee a 
where e.effdt = (Select min(b.effdt) 
                 from employee b 
                  where e.id= b.id 
                 and e.status= b.status)

It returns two rows:

ID  EFFDT       STATUS
1   2001-01-01  A    
1   2003-01-01  B

Expected output :

ID   EFFDT        STATUS
1    2001-01-01   A
1    2003-01-01   B
1    2005-01-01   A
1    2006-01-01   B

I need the minimum effective dated row before a status was changed for the same employee multiple times.

Any help would be really appreciated. Thanks.

Try this:

SELECT id, effdt, status
FROM (
  SELECT e.*,
       CASE WHEN id <> @last_id THEN 1
            WHEN status <> @last_status THEN 1
            ELSE 0
       END take_this_row,
       @last_id := id last_id,
       @last_status := status
  FROM employee e
  cross join (
    SELECT @last_id := -111,
           @last_status := 'XXX'
  ) init_var
  ORDER BY id, effdt
) q
WHERE take_this_row = 1

demo --> http://www.sqlfiddle.com/#!2/dec99c/7


EDIT

A query for Oracle:

SELECT id, effdt, status
FROM (
  SELECT e.*,
       CASE lag( status ) over (partition by id order by effdt )
            WHEN status THEN 0
            ELSE 1
       END take_this_row
  FROM employee e
)
WHERE take_this_row = 1
ORDER BY id, effdt

Demo --> http://www.sqlfiddle.com/#!4/1d27f/5



This query will probaby run also on DB2, unfortunately I have no DB2 installed on my PC and cannot test it.
I've found here: https://www.ibm.com/developerworks/community/blogs/dbtrue/entry/lag_lead_first_value_last_value_totally_new_in_db21?lang=en
that in DB2 9.7 they have implemented analytic functions LAG, LEAD etc (in their terminology "OLAP functions"), therefore this query should work on DB2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM