ROW_NUMBER() OVER函数没有运行遍历所有记录

ROW_NUMBER() OVER Function did not run through all records

我有一个table这样的

ID  Date    Sale    Sale_desc
1   1/1/2017    10  book
1   1/1/2017    10  book
1   1/1/2017    10  book
2   1/2/2017    12  notebook
2   1/2/2017    12  notebook
3   1/3/2017    1   pen
3   1/3/2017    1   pen

我运行以下查询获取行号:

select *, row_number() over (partition by id order by date) 
from the_table;

但是结果不是我所期望的。

ID  Date        Sale    Sale_desc   row_num
1   1/1/2017    10      book        1
1   1/1/2017    10      book        1
1   1/1/2017    10      book        1
2   1/2/2017    12      notebook    1
2   1/2/2017    12      notebook    2
3   1/3/2017    1       pen         1
3   1/3/2017    1       pen         2

前 3 行的 row_num 应该是 1、2、3,但看起来 row_num() 没有 运行 遍历所有行。请帮忙。谢谢

我猜你的 id 列是字符串 (VARCHAR/CHAR)。你可以试试:

select *, row_number() over (partition by CAST(id AS INTEGER) order by date) 
from the_table;

Rextester demo

当我运行同样的代码时,我得到了你期望的结果。我对可能与您使用的列类型不同的列类型做了一些假设。我正在使用默认排序规则进行测试,这会影响字符串比较。

如果您 运行 相同的测试用例并得到正确的结果,那么问题出在代码的其他地方。我们需要查看更多原始查询和架构才能找到问题。

declare @Test table
(
    ID int,
    [Date] Date,
    Sale int,
    Sale_desc varchar(50)
)

insert into @Test
(ID, [Date], Sale, Sale_desc)
select 1, '1/1/2017', 10, 'book'     union all
select 1, '1/1/2017', 10, 'book'     union all
select 1, '1/1/2017', 10, 'book'     union all
select 2, '1/2/2017', 12, 'notebook' union all
select 2, '1/2/2017', 12, 'notebook' union all
select 3, '1/3/2017', 1 , 'pen'      union all
select 3, '1/3/2017', 1 , 'pen'

select
    *,
    row_number() over (partition by id order by [date]) as row_num
from @test

结果:

ID  Date        Sale  Sale_desc   row_num
1   2017-01-01  10    book        1
1   2017-01-01  10    book        2
1   2017-01-01  10    book        3
2   2017-01-02  12    notebook    1
2   2017-01-02  12    notebook    2
3   2017-01-03  1     pen         1
3   2017-01-03  1     pen         2