OVER PARTION BY 没有订购

OVER PARTITION BY without ordering

我有一个 table,我只想从中检索每组记录中的最新记录,由特定字段中的值标记。

table 内容看起来像这样:

state   date
512     2021-03-09 11:31:38.300
512     2021-03-09 11:31:38.300
512     2021-03-09 11:31:31.693
512     2021-03-09 11:31:31.693
512     2021-03-08 12:49:10.753
512     2021-03-08 12:35:47.357
514     2021-03-08 12:35:01.030
512     2021-03-08 12:33:48.050
514     2021-03-08 12:14:29.537
514     2021-03-08 12:14:29.537
514     2021-03-08 12:14:18.760
512     2021-03-08 12:14:05.597

我想像这样使用 OVERPARTITIONSELECT 输出:

row state   date
1   512     2021-03-09 11:31:38.300
2   512     2021-03-09 11:31:38.300
3   512     2021-03-09 11:31:31.693
4   512     2021-03-09 11:31:31.693
5   512     2021-03-08 12:49:10.753
6   512     2021-03-08 12:35:47.357
1   514     2021-03-08 12:35:01.030
1   512     2021-03-08 12:33:48.050
1   514     2021-03-08 12:14:29.537
2   514     2021-03-08 12:14:29.537
3   514     2021-03-08 12:14:18.760
1   512     2021-03-08 12:14:05.597

如您所见,行按 date DESC 排序,state 字段根据每个更改从 1 开始的 row 字段分组在 state 字段中。

目前,我的代码如下所示:

with query as
(
    select state, date, row = row_number() over (partition by state order by date desc)
    from table
)
select t.*
from table t
inner join query q on t.state = q.state and t.date = q.date
where row = 1
order by t.date desc

不幸的是,这似乎是在按 date DESC 对记录进行排序之前按 state 对记录进行分组,因此结果只有两个结果集记录,因为 [=17] 中只有两个不同的值=] 字段。应该(对于上面的示例数据)有 5 个结果集记录。

如何正确编号分区组?

这可行,但可能有更简单的方法。

WITH
cte1 AS
(
    SELECT 
        ROW_NUMBER() OVER(ORDER BY date_ DESC) as dateRow,
        ROW_NUMBER() OVER(PARTITION BY state ORDER BY date_ DESC) as stateRow,
        state,
        date_
    FROM    StateDate
)
SELECT 
    ROW_NUMBER() OVER(PARTITION BY state, (dateRow - stateRow)  ORDER BY date_ DESC) as row,
    state, date_
FROM cte1
ORDER BY date_ DESC, state

这是我使用的数据设置:

CREATE TABLE StateDate( state INT, date_ DATETIME)
GO

--state   date
INSERT INTO StateDate VALUES (512, '2021-03-09 11:31:38.300');
INSERT INTO StateDate VALUES (512, '2021-03-09 11:31:38.300');
INSERT INTO StateDate VALUES (512, '2021-03-09 11:31:31.693');
INSERT INTO StateDate VALUES (512, '2021-03-09 11:31:31.693');
INSERT INTO StateDate VALUES (512, '2021-03-08 12:49:10.753');
INSERT INTO StateDate VALUES (512, '2021-03-08 12:35:47.357');
INSERT INTO StateDate VALUES (514, '2021-03-08 12:35:01.030');
INSERT INTO StateDate VALUES (512, '2021-03-08 12:33:48.050');
INSERT INTO StateDate VALUES (514, '2021-03-08 12:14:29.537');
INSERT INTO StateDate VALUES (514, '2021-03-08 12:14:29.537');
INSERT INTO StateDate VALUES (514, '2021-03-08 12:14:18.760');
INSERT INTO StateDate VALUES (512, '2021-03-08 12:14:05.597');
GO