我有一个以 ID 作为主键(也是身份)和 datetimestamp 列的表。我需要使用按时间戳值排序的 ID 更新表,如下所示。并非所有 ID 都存在。ID 是正确的,日期时间戳是混乱的,需要排序。
当前数据的数据库表为 -
id datetimestamp
-- -----------------------
1 2013-08-08 14:08:43.560
2 2013-08-05 14:08:46.963
4 2013-08-06 14:08:53.247
5 2013-08-04 14:08:55.610
6 2013-08-03 14:08:58.543
8 2013-08-05 14:08:46.963
9 2013-08-06 14:08:53.247
10 2013-08-04 14:08:55.610
11 2013-08-03 14:08:58.543
所需数据为 -
id datetimestamp
-- -----------------------
1 2013-08-03 14:08:58.543
2 2013-08-03 14:08:58.543
4 2013-08-04 14:08:55.610
5 2013-08-04 14:08:55.610
6 2013-08-05 14:08:46.963
8 2013-08-05 14:08:46.963
9 2013-08-06 14:08:53.247
10 2013-08-06 14:08:53.247
11 2013-08-08 14:08:43.560
下面是可以创建示例数据的脚本 -
create table #tmp_play
(id int identity (1,1) primary key, datetimestamp datetime)
insert into #tmp_play values (getdate());
insert into #tmp_play values (getdate()-3);
insert into #tmp_play values (getdate()-1);
insert into #tmp_play values (getdate()-2);
insert into #tmp_play values (getdate()-4);
insert into #tmp_play values (getdate()-5);
delete from #tmp_play where id = 3
insert into #tmp_play (datetimestamp)
select datetimestamp from #tmp_play
delete from #tmp_play where id = 7
我尝试了以下方法,但由于缺少 ID,因此无法使用。
with sorted as
(select top 100 ROW_NUMBER() OVER(ORDER BY datetimestamp) as RowNum, *
from #tmp_play order by datetimestamp)
update t
set t.datetimestamp = s.datetimestamp
from #tmp_play t
join sorted s on t.id = s.RowNum
知道如何对这些数据进行排序吗?