如何获得最新的活跃记录

时间:2017-07-29 07:57:25

标签: oracle oracle11g oracle-sqldeveloper

这是我的数据。会员可以多次注册并可以随时更改计划,我需要获取C_level数据,以获取ID为1的“8/1/2017”的最新版本,因为ID 2没有最新数据,我们必须显示12/31/2016记录。

ID Start_Date End_Date   C_Level
1  1/1/2016  12/31/2016    1
1  1/1/2017  8/1/2017      2
1  9/1/2017  12/31/2017    3
1  1/1/2018  12/31/2018    0
2  1/1/2015  12/31/2015    2
2  1/1/2016  12/31/2016    3

1 个答案:

答案 0 :(得分:1)

如果我理解您的要求,那么此查询应该提供您想要的内容:

WITH current_running AS (
  SELECT to_date( '8/1/2017','mm/dd/rrrr') As Current_running_date
  FROM dual
)
SELECT * FROM (
   SELECT t.*,
          row_number() Over (partition by id order by end_date desc ) As rn,
          c.Current_running_date
   FROM Table1 t
   JOIN current_running c
   ON c.Current_running_date >= ANY( t.Start_Date, t.End_Date )
)
WHERE rn = 1
;

演示:http://api.jquery.com/toggle/

对于current_running_date = 2017-08-01,它给出:

| ID |            START_DATE |              END_DATE | C_LEVEL | RN | CURRENT_RUNNING_DATE |
|----|-----------------------|-----------------------|---------|----|----------------------|
|  1 | 2017-01-01 00:00:00.0 | 2017-08-01 00:00:00.0 |       2 |  1 | 2017-08-01T00:00:00Z |
|  2 | 2016-01-01 00:00:00.0 | 2016-12-31 00:00:00.0 |       3 |  1 | 2017-08-01T00:00:00Z |

而对于current_running_date = 2016-07-15

| ID |            START_DATE |              END_DATE | C_LEVEL | RN | CURRENT_RUNNING_DATE |

|----|-----------------------|-----------------------|---------|----|----------------------|
|  1 | 2016-01-01 00:00:00.0 | 2016-12-31 00:00:00.0 |       1 |  1 | 2016-07-15T00:00:00Z |
|  2 | 2016-01-01 00:00:00.0 | 2016-12-31 00:00:00.0 |       3 |  1 | 2016-07-15T00:00:00Z |