oracle 基于多列的排名

iugsix8n  于 2023-06-29  发布在  Oracle
关注(0)|答案(2)|浏览(131)

enter image description here我有一个3列的表如下。我需要写一个查询,以找出是否有任何订单后,断开订单的基础上,订单日期。也就是说,如果一个帐户有多个订单,我想对它们进行排名,并检查Disconnect是否具有最高排名(如果disconnect订单相对于帐户具有最高排名,则disconnect是最后一个订单)。先谢谢你了。

Account no, Order, Order_date
101,Connect,1-1-2023
101,Modify,1-3-2023
103,Connect,1-2-2023
101,Disconnect,1-3-2023

我试过了-

SELECT account_no,order_id,order_date,RANK() OVER (ORDER BY created_t asc)rank_no
FROM table;
ippsafx7

ippsafx71#

我需要写一个查询,以找出是否有任何订单后,断开订单的基础上,订单日期。
添加一个PARTITION BY子句,并将ORDER BY子句从ASC更改为DESC,以便最新的行始终排名第一,然后您可以检查排名第一的行的order_id是否为Disconnect。如果你需要检查至少有一行的order_idDisconnect,那么你可以使用COUNT解析函数和CASE表达式:

SELECT *
FROM   (
  SELECT account_no,
         order_id,
         order_date,
         RANK() OVER (
           PARTITION BY account_no
           ORDER BY created_t DESC
         ) AS rank_no,
         COUNT(CASE order_id WHEN 'Disconnect' THEN 1 END) OVER (
           PARTITION BY account_no
         ) AS has_disconnect
  FROM   table_name
)
WHERE rnk      = 1
AND   order_id != 'Disconnect'
AND   has_disconnect > 0;

或者,在Oracle 12中,您可以使用MATCH_RECOGNIZE

SELECT *
FROM   table_name
MATCH_RECOGNIZE(
  PARTITION BY account_no
  ORDER BY created_t DESC
  ALL ROWS PER MATCH
  PATTERN ( ^ not_disconnect {- any_row*? disconnect -} )
  DEFINE
    not_disconnect AS order_id != 'Disconnect',
    disconnect     AS order_id =  'Disconnect'
);
pepwfjgg

pepwfjgg2#

您也可以使用EXISTS来找出这样的条件,以获得具有相同account_no的Disconnect的类型不同的行:

select d.* from table_name d
where order_id <> 'Disconnect'
    and exists(
        select 1 from table_name d1 
            where d1.account_no = d.account_no 
            -- or <= depending on your requirements
            and d1.order_date < d.order_date
            and d1.order_id = 'Disconnect'
    )
;

如果您希望Disconnect行后面有一个not Disconnect:

select d.* from table_name d
where order_id = 'Disconnect'
    and exists(
        select 1 from table_name d1 
            where d1.account_no = d.account_no 
            -- or >= depending on your requirements
            and d1.order_date > d.order_date
            and d1.order_id <> 'Disconnect'
    )
;

相关问题