根据更改选择“上一个”和“当前”值

时间:2018-01-23 12:46:23

标签: sql oracle

我想从下表中选择产品的先前和当前客户。 PREV_DAY表包含产品前一天的最新客户设置,CURR_DAY表设置后续更改。 RANKING列显示更改的顺序,其中值1是最新更改。所以我要做的是产品100,CURR_DAY结束时的更改应该是,

**PREV_CUST** XYZ     **CURRENT_CUST** ABC then,
**PREV_CUST** ABC     **CURRENT_CUST** DEF

我无法正确排序。

此致 SV

CREATE TABLE PREV_DAY (ID NUMBER, CHANGE_TIME DATE, PROD_ID NUMBER, CUSTOMER VARCHAR2(10));
CREATE TABLE CURR_DAY (ID NUMBER, CHANGE_TIME DATE, PROD_ID NUMBER, CUSTOMER VARCHAR2(10), RANKING NUMBER);

INSERT INTO PREV_DAY VALUES (1, SYSDATE-1, 100, 'XYZ');
INSERT INTO PREV_DAY VALUES (2, SYSDATE-1, 200, 'EFG');

INSERT INTO CURR_DAY VALUES (1, SYSDATE, 100, 'ABC', 2);
INSERT INTO CURR_DAY VALUES (2, SYSDATE, 100, 'DEF', 1);
INSERT INTO CURR_DAY VALUES (3, SYSDATE, 200, 'IJK', 1);

COMMIT;

1 个答案:

答案 0 :(得分:0)

只需使用change_timeranking(降序)进行排序。对于您提供的数据,它将类似于:

select change_time, ranking, prev, curr
  from (
    select lag(customer) over (order by change_time, ranking desc) prev, 
           customer curr, change_time, ranking
      from (select id, change_time, prod_id, customer, ranking 
              from curr_day where prod_id = 100 
            union all
            select id, change_time, prod_id, customer, null    
              from prev_day where prod_id = 100) )
  where change_time >= trunc(sysdate)

如果数据在一个表格中,您不需要union,请过滤日期。

结果:

CHANGE_TIME          RANKING  PREV        CURR
-------------------  -------  ----------  ----------
2018-01-23 15:04:01        2  XYZ         ABC
2018-01-23 15:04:01        1  ABC         DEF