如有其他问题,请仅使用文字,不要使用图像。
您的数据示例
create table my_table(
id int,
date date ,
pro_name varchar(10),
count_item int );
insert into my_table values
(1,'2024-01-27','PRO-001',10),(2,'2024-01-28','PRO-002',15),
(3,'2024-01-29','PRO-003',20),(4,'2024-01-30','PRO-004',40),
(5,'2024-01-22','PRO-005',30),(6,'2024-01-23','PRO-006',10),
(7,'2024-01-31','PRO-007',50),(8,'2023-12-25','PRO-008',70),
(9,'2023-12-26','PRO-009',30),(10,'2024-01-28','PRO-010',80);
查询
with cte as (
select *,
row_number() over( order by date asc,id asc ) as s_n
from my_table
) select * from cte
order by id asc;
结果
id date pro_name count_item s_n
1 2024-01-27 PRO-001 10 5
2 2024-01-28 PRO-002 15 6
3 2024-01-29 PRO-003 20 8
4 2024-01-30 PRO-004 40 9
5 2024-01-22 PRO-005 30 3
6 2024-01-23 PRO-006 10 4
7 2024-01-31 PRO-007 50 10
8 2023-12-25 PRO-008 70 1
9 2023-12-26 PRO-009 30 2
10 2024-01-28 PRO-010 80 7
关键部分是
order by date asc,id asc
,它首先按日期对行进行排序,对于相同的日期,首先按最小 id 排序。
请注意,我使用了正确的日期数据类型。
现在,如果 s_n 是您要尝试更新的列,请使用
with To_Update as
(
select id,
date,
pro_name,
count_item,
row_number() over( order by date asc,id asc ) as s_n
from my_table
)
update my_table m
inner join To_Update t on m.id=t.id
set m.s_n=t.s_n;