oracle ROW_NUMBER()over(Partition by....)返回特定行

xlpyo6sf  于 2023-08-04  发布在  Oracle
关注(0)|答案(2)|浏览(147)

我的查询看起来像这样:

with T1 as (
Select
Dept_No,
Product_No,
Order_No,
Order_Type
Row_number() over (partition by Product_ID order by Order_No desc) as "COUNT"

From Orders_Table)

Select * from T1
where ("COUNT"  = '1' and "Order_Type" <> 'Cancel')
or ("COUNT" = '2' AND "Order_Type" <> 'Cancel'

字符串
所以我想调出最近一个没有取消的订单。
本质上,我的ROW_number()over(partition by...)函数按顺序标记订单,1是最近的订单,2是第二个最近的订单。
问题是,使用此查询,它会拉取最近的订单和第二个最近的订单。
我试着把这个写到哪里,如果它只给一个或另一个。
因此,如果COUNT = 1并且order_type不是cancel,则只显示该记录。
如果没有,给我看第二张。
这是在Toad for Oracle 9.5中使用SQL选项卡完成的。

l2osamch

l2osamch1#

但你还有手术室。
如果两个或都满意,您将获得两行。

with T1 as (
Select
Dept_No,
Product_No,
Order_No,
Order_Type
Row_number() over (partition by Product_ID order by Order_No desc) as "COUNT"
From Orders_Table
where "Order_Type" <> 'Cancel')

Select * from T1
where "COUNT"  = '1'

字符串

uqzxnwby

uqzxnwby2#

使用case表达式来控制哪些行从row_number()获得结果,这里我们避免对任何已取消的行进行编号:

WITH t1 AS (
      SELECT
            Dept_No
          , Product_No
          , Order_No
          , Order_Type
            /*  the most recent order that was not canceled */
          , case when order_type <> 'Cancel' 
                 then ROW_NUMBER() OVER (PARTITION BY Product_ID 
                                          ORDER BY Order_No DESC)
                 end AS is_recent
       FROM Orders_Table
      )
SELECT
      *
FROM t1
WHERE is_recent = 1

字符串
或者,也许最简单的方法是简单地排除已取消的订单,例如:

WITH t1 AS (
      SELECT
            Dept_No
          , Product_No
          , Order_No
          , Order_Type
          , ROW_NUMBER() OVER (PARTITION BY Product_ID 
                                          ORDER BY Order_No DESC)
                 AS is_recent
       FROM Orders_Table
       WHERE order_type <> 'Cancel' 
      )
SELECT
      *
FROM t1
WHERE is_recent = 1


nb:row_number()返回整数,所以不要将该列与字符串进行比较

相关问题