对表中的数据进行排序

时间:2013-08-08 13:30:07

标签: sql sql-server

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

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

2 个答案:

答案 0 :(得分:4)

为什么订单甚至重要?对于应用程序或业务而言,id 1具有比id 2更小/更大的时间值应该无关紧要。我理解您正在尝试修复被认为是错误数据的内容,但这确实不应该影响您的应用程序。我也同意这个序列号可能更好,因为它没有提供太多的价值。

话虽如此,为了解决手头的问题,你需要得到两组序列号。 1表示datetimestamp,另一个表示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

答案 1 :(得分: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