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

时间:2014-09-29 14:20:51

标签: sql oracle window-functions row-number

我的查询如下:

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未取消,则只显示该记录。如果没有,那么告诉我第二个。

非常感谢您的帮助。这是使用SQL选项卡在Toad for Oracle 9.5中完成的。

2 个答案:

答案 0 :(得分: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 "COUNT"
From Orders_Table
where "Order_Type" <> 'Cancel')

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

答案 1 :(得分:0)

使用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()返回一个整数,所以不要将该列与字符串进行比较