2

如何根据另一列更新具有增加 ID 的 sql server?

我有一个具有以下结构的表:

sn  name    val
    test     0
    test     0.5
    test     2
    test1    0
    test1    0.5
    test1     2

我如何更新它,这将是:

sn  name      val
1    test      0
2    test      0.5
3    test      2
1    test1     0
2    test1     0.5
3    test1     2

小提琴

4

3 回答 3

2

使用 cte 和 row_number

这是一个例子:

create table #mytable (sn int, name varchar(20), val money)

insert into #mytable values (null, 'test', 0.5)
insert into #mytable values (null, 'test', 1)
insert into #mytable values (null, 'test1', 0.5)
insert into #mytable values (null, 'test1', 1)

;with cte as (select row_number() over (order by name, val) as rn, * from #mytable)
update cte set sn = rn

select * from #mytable
于 2013-10-30T08:36:40.260 回答
1

如果表中有键列,则可以使用Row_Number()OVER ... PARTITION BY子句轻松完成此操作。我添加了一个专栏:Id int identity primary key这是更新:

;with RowNumberedData as (
  select 
    id, 
    row_number() over (
      partition by name
      order by id
    ) as rowno
  from sql_test
)
update s
  set sn = r.rowno
from sql_test s
join RowNumberedData r
  on s.id = r.id;

SQLFiddle:http ://sqlfiddle.com/#!3/43fa8/4

于 2013-10-30T08:44:40.163 回答
1

你应该使用ROW_NUMBER()函数。同样,一旦您必须为每个 NAME 值启动新计数器,您应该PARTITON by NAME在此语句中使用。

WITH T AS 
(select sql_test.*,
        ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Val) as RowNumber
        from sql_test)
UPDATE T SET SN=RowNumber;

SQLFiddle 演示

于 2013-10-30T08:50:01.780 回答