我有一个像下面的表结构
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万条记录。
答案 0 :(得分: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小提示演示is available。