简体   繁体   中英

Selecting Active Rows using a Start and End Date

I would like to see records that are active at a certain point in time based on two date fields: 1) the Process_DT and the 2) Process_End_DT. My table follows a convention of preserving history for each CUST_ID by inserting a new record instead of updating the record. When this happens, the new record has an Process_DT is set to now() and the Process_End_DT is set to 31-DEC-9999. Then Process_End_DT of the original record is set to now(). So to put in some context, Cust_ID 1 became a customer on 27-FEB-2015 and they are still active. Cust_ID 3 became a customer on 15-APR-2014 but that ended on 27-FEB-2014.

Cust_Id   Process_DT    Process_End_DT Active
---------------------------------------------
1         27-FEB-2016   31-DEC-9999    1
3         15-APR-2014   27-FEB-2017    0

I am sure this convention has a name... bonus points if you know the name of it. I want to find the active records at given points in time. The active column is not part of the table, that's just to clarify.

ID  Cust_Id   Process_DT    Process_End_DT Active
-----------------------------------------------
001  1        27-FEB-2016   31-DEC-9999   1
002  1        01-JAN-2015   27-FEB-2016   0
003  1        04-SEP-2014   01-JAN-2015   0
004  2        01-MAR-2016   31-DEC-9999   1
005  3        15-APR-2014   27-FEB-2017   0

So for my dummy data, the rows active on 31-DEC-2016 would be 001, 004, and 005. The rows active on 31-DEC-2015 would be 002 and 005. The rows active on 31-DEC-2014 would be 003 and 005.

Use the WHERE clause to check if the specified time point refers to the activity interval.

SELECT *
FROM MyTable
WHERE @TimePoint BETWEEN Process_DT AND Process_End_DT;

If you want to see the active rows at the current time, use NOW() instead of @TimePoint .

This is a type-2 dimension table (or some similar name). Just use basic inequalities:

select t.*
from t
where date '2016-12-01' >= process_dt and
      date '2016-12-01' < process_end_dt;  -- may be <=

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