Sql查询从表中获取第二个最新条目

时间:2018-05-02 12:22:36

标签: sql oracle teradata

我有一张下面提到的列的表。我想获取以前的客户状态。一旦客户ID可以有多个条目

Customer_id   status     start_date    end_date   Active
1             Member      01-JAN-18    04-FEB-18   N
1             Explorist   05-FEB-18    30-APR-18   N
1             Globalist   01-MAY-18    31-DEC-99   Y

期望的输出

Customer _id     Previous_status   end_date
1                Explorist          30-APR-18

5 个答案:

答案 0 :(得分:2)

请使用QUALIFY关键字和ROW_NUMBER()尝试以下查询:

SELECT a.* from table a 
QUALIFY ROW_NUMBER OVER(PARTITION BY customer_id order by start_date desc) = 2

答案 1 :(得分:0)

以下查询应该有效。

SELECT * from (
SELECT a.*, 
ROW_NUMBER() over (partition by customer_id order by start_date desc) rn
 from table a ) 
where rn =2 

答案 2 :(得分:0)

您可以使用以下查询,我想这很简单,对我有用,

val input_json = {"name" : "john", "id" : 101}

答案 3 :(得分:0)

请考虑以下问题:Select Nth Row From A Table In Oracle

在你的情况下,那将是:

select * from (select a.*, rownum rnum from (select * from <your table name> 
order by <start_date or end_date> desc) a where rownum <= 2) where rnum >= 2;

答案 4 :(得分:0)

如果您使用的是Oracle DataBase,请使用 ROW_NUMBER()功能尝试以下查询:我们认为表名是客户


    SELECT TEMP.CUSTOMER_ID
          ,TEMP.STATUS
          ,TEMP.START_DATE
          ,TEMP.END_DATE
          ,TEMP.ACTIVE 
          FROM(
            SELECT ROW_NUMBER() OVER (PARTITION BY CUSTOMER_ID ORDER BY CUSTOMER_ID ASC,START_DATE DESC) AS "ROW_NUM"
                  ,CUSTOMER_ID
                  ,STATUS
                  ,START_DATE
                  ,END_DATE
                  ,ACTIVE
                  FROM CUSTOMER) TEMP 
                      WHERE TEMP."ROW_NUM" = 2;