5

我有一个如下表结构

id  wstage      wstatus wdate
101 Unaquired   create  2013-08-29 17:07:20.040
101 Unaquired   rework  2013-08-29 18:07:20.040
101 inprocess   accqui  2013-08-29 19:07:20.040
101 inprocess   alloca  2013-08-29 20:07:20.040
101 Unaquired   create  2013-08-29 21:07:20.040
101 Unaquired   rework  2013-08-29 22:07:20.040

我必须像这样编号

id  wstage      wstatus wdate                   rownumber
101 Unaquired   rework  2013-08-29 22:07:20.040 1
101 Unaquired   create  2013-08-29 21:07:20.040 1
101 inprocess   alloca  2013-08-29 20:07:20.040 2
101 inprocess   accqui  2013-08-29 19:07:20.040 2
101 Unaquired   rework  2013-08-29 18:07:20.040 3
101 Unaquired   create  2013-08-29 17:07:20.040 3

我正在尝试使用功能

select *,ROW_NUMBER() over (partition by id,wstage order by wdate desc) rownumber

但这并没有提供所需的输出。我不想使用 pl/sql 是否有排名功能或简单查询来实现这一点。我的表有 5000 万条记录。

4

1 回答 1

4

假设wdate每个值是唯一的id,这可能会起作用:

WITH partitioned AS (
  SELECT
    *,
    grp = ROW_NUMBER() OVER (PARTITION BY id         ORDER BY wdate DESC)
        - ROW_NUMBER() OVER (PARTITION BY id, wstage ORDER BY wdate DESC)
  FROM atable
),
maxdates AS (
  SELECT
    id, wstage, wstatus, wdate,
    maxwdate = MAX(wdate) OVER (PARTITION BY id, wstage, grp)
  FROM partitioned
)
SELECT
  id, wstage, wstatus, wdate,
  rownumber = DENSE_RANK() OVER (PARTITION BY id ORDER BY maxwdate DESC)
FROM maxdates
;

第一个 CTE 确定不同的id, wstage岛,第二个 CTE 找到wdate每个岛的最大值,主查询根据找到的最大值对行进行排名。

SQL Fiddle 演示可用于此查询。

于 2013-08-29T13:52:08.620 回答