使用没有唯一ID的row_numbers更新表

时间:2018-01-30 17:12:41

标签: sql-server sql-update row-number

我有一张旅行时间表,每天分为288个5分钟的时间段。我想每天从0-287创建这些时期的计数。因此,计数每天都会重置,因此每天的计数为0-287。我得到了这么远,但我得到了错误的语法错误。

update [dbo].[table]
   set count = count2 
  from (
    select 
       row_number() over (partition by date order by epoch) as count2 
    from [dbo].[table]
  )

2 个答案:

答案 0 :(得分:0)

要更正代码中的语法错误,请尝试以下操作:

Update  [dbo].[table]  set count = t.count2 -1
from (select datecol, epoch, row_number() over (partition by datecol 
order by epoch) as count2 from  [dbo].[table] ) t
inner join [dbo].[table] tt on t.datecol = tt.datecol and t.epoch = tt.epoch

答案 1 :(得分:0)

您需要告诉sql server您要更新的行。 SQL Server不知道您希望如何加入这些表。

首先,我会确保计数看起来没问题。

select 
    date,
    epoch,
    row_number() over (partition by date order by epoch) as count2 
from [dbo].[table]

修改

我没有测试我的答案,抱歉。 这应该有效:

update dbo.table
    set count = c2.rnc
from dbo.table
join (
    select
        epoch,
        date,
        ROW_NUMBER() over (partition by date order by epoch) as rnc
    from dbo.table
) as c2
    on c2.epoch = table.epoch
    and c2.date = table.date