-2

我有一个以 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

知道如何对这些数据进行排序吗?

4

2 回答 2

4

为什么顺序甚至很重要?对于应用程序或业务来说,id 1 的时间价值比 id 2 更小/更大。我知道您正在尝试修复被认为是错误的数据,但这确实不应该影响您的应用程序。我也同意这个序列号可能更好地派生,因为它没有提供太多价值。

话虽如此,要解决手头的问题,您需要获得两组序列号。1 用于日期时间戳,另一个用于 id。然后,您可以加入这两个以更新行。

;with Id_Order
AS
(
select *, id_seq = ROW_NUMBER() over(order by id)
from #tmp_play
),
Dt_Order
as
(
select *, dt_seq = ROW_NUMBER() over(order by datetimestamp asc)
from #tmp_play
)
update a
set datetimestamp = dt.datetimestamp
from Id_Order a
inner join Dt_Order dt
    on a.id_seq = dt.dt_seq
于 2013-08-08T13:58:03.033 回答
1

试试这个...

update #tmp_play
set datetimestamp = s.datetimestamp
    from 
        #tmp_play
    inner join      
    (
        select *, ROW_NUMBER() over (order by id) rn
        from #tmp_play
    ) p
        on #tmp_play.id = p.id
    inner join 
    (
    select *, ROW_NUMBER() over (order by datetimestamp) rn1 from #tmp_play
    ) s
        on p.rn = s.rn1
于 2013-08-08T14:00:15.090 回答