将1添加到表中的每个记录的字段中

时间:2014-04-04 09:17:48

标签: sql-server procedure

我有一张表记录:

ID Name RecordId GroupField
1  asd  1        Group1
2  asd2 1        Group1
3  asd3 1        Group1
4  asd4 1        Group2
5  asd5 1        Group2

我需要的是一个查询什么会根据我的记录组更新RecordId列。结果将如下所示:

ID Name RecordId GroupField
1  asd  1        Group1
2  asd2 2        Group1
3  asd3 3        Group1
4  asd4 1        Group2
5  asd5 2        Group2

RecordId必须从1开始增加数字,需要重置并从每个组的1开始。

2 个答案:

答案 0 :(得分:2)

您可以尝试使用ROW_NUMBER

类似

;WITH Vals AS (
  SELECT ID, ROW_NUMBER() OVER (PARTITION BY GroupField ORDER BY ID) NewID
  FROM Table1
 )
UPDATE Table1
SET RecordID = NewID
FROM Table1 t INNER JOIN
Vals v ON t.ID = v.ID

SQL Fiddle DEMO

答案 1 :(得分:1)

试试这个,

;With CTE as 
(
select *
    ,RANK() over (partition by GroupField order by ID) as RnK
 from myTableSort
 )
 update myTableSort set RecordID = CTE.RnK
 from CTE where CTE.ID = myTableSort.ID

<强> Demo