5

如何让第一行过滤掉一些值?我使用 row_number() over(partition by Name ORDER BY Date) 来获取订单(参见下面的示例)。但我需要,排名将从最后一次出现 Type = B 开始(参见预期输出)

SELECT Name, Age, Type, Date, 
       row_number() over(partition by Name ORDER BY Date) as Rank
FROM TableA;

例如 :

Name   Age   Type   Date          Rank
Ben    12      A    2013/02/01    1 
Rod    14      A    2013/02/05    2
Zed    13      B    2013/03/09    3
Ken    12      A    2013/04/02    4 
Jed    14      B    2013/05/01    5
Mar    13      A    2013/05/04    6
Nic    12      A    2013/06/02    7
Jen    15      A    2013/06/09    8

预期输出:

Name   Age    Type   Date         Rank
Mar    13      A    2013/05/04    1
Nic    12      A    2013/06/02    2
Jen    15      A    2013/06/09    3
4

4 回答 4

4

尝试

WITH qry AS 
(
  SELECT "Name", "Age", "Type", "Date", 
         ROW_NUMBER() OVER (PARTITION BY "Type" ORDER BY "Date") rank
  FROM TableA
)
SELECT "Name", "Age", "Type", "Date"
  FROM qry
 WHERE rank = 1

输出:

| NAME | AGE | TYPE |                            DATE |
-------------------------------------------------------
|  Ben |  12 |    A | February, 01 2013 00:00:00+0000 |
|  Zed |  13 |    B |    March, 09 2013 00:00:00+0000 |

这是SQLFiddle演示

于 2013-06-07T07:11:12.813 回答
2

还有另一种可能性:您可以将其包装在子查询中:

select
    t.*
  from
    (SELECT "Name", "Age", "Type", "Date", 
         ROW_NUMBER() OVER (PARTITION BY "Type" ORDER BY "Date") rank
       FROM TableA
     ) t
  where
    rank = 1

“子查询”和“公用表表达式( with)”的行为不同,因此请查看这些方法。这取决于您的情况,如果一个是强制性的(处理副作用)或者一个更快。在Oracle的情况下,甚至有一个materialize提示。“根据 SQL 标准,CTE 提供了优化围栏功能”(这是来自此处的改编引文)。

于 2013-06-07T07:58:55.383 回答
0

这也应该满足您的要求:

select t.*,
       row_number() over(partition by "Name" ORDER BY "Date") as Rank
from  TableA t
where "Date" >= (select max("Date") from TableA where "Type" = 'B')
于 2013-06-07T10:54:18.587 回答
0

尝试这个:

SELECT Name, Age, Type, Date, 
       row_number() over(partition by Name ORDER BY Date) as Rank
FROM TableA
WHERE type <> 'B'
AND Date > (
    SELECT max(Date)
    FROM TableA
    WHERE type = 'B'
);

请注意,这假设在与最后一个 B 完全相同的日期/时间没有 A。

于 2013-06-07T09:46:22.110 回答