如何在SQL中基于Date列进行排序时更新表?

时间:2016-11-30 20:12:59

标签: sql-server sorting

表格的第一列是日期。

我需要在根据日期(降序)实际更新表时对其余数据进行排序。我不能一起使用UPDATE和ORDER BY。

我尝试使用类似这篇文章的内容:

    app.get('/*', function (req, res, next) {
       if (/.js|.html|.css|templates|js|scripts/.test(req.path) || req.xhr) {
       return next({ status: 404, message: 'Not Found' });
       } else {
          return res.render('index');
       }
    });

in

SQL Server: UPDATE a table by using ORDER BY

但我不能混淆UPDATE Test SET Number = rowNumber FROM Test INNER JOIN (SELECT ID, row_number() OVER (ORDER BY ID DESC) as rowNumber FROM Test) drRowNumbers ON drRowNumbers.ID = Test.ID 和约会。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

使用CTE:

在此处查看:http://rextester.com/NGTM78965

create table #t1 (id int, d datetime, rown int);
insert into #t1 values (1,'2016-05-01',0);
insert into #t1 values (2,'2016-05-04',0);
insert into #t1 values (3,'2016-06-01',0);
insert into #t1 values (4,'2016-04-03',0);
insert into #t1 values (5,'2016-05-12',0);
insert into #t1 values (6,'2016-08-01',0);
insert into #t1 values (7,'2016-05-15',0);
insert into #t1 values (8,'2016-05-25',0);

with cte (id, d, r) as
(
select id, d, row_number() over (order by d) r 
from #t1
)
update #t1
set #t1.rown = cte.r
from cte inner join #t1 on #t1.id = cte.id;

select * from #t1 order by d