سؤال

I havea table Records:

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

What i need is a query what would update the RecordId column based on what group is my record in. The result would looks like this:

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 has to to be growing number starting from 1 and needs to reset and start from 1 for every group.

هل كانت مفيدة؟

المحلول

You could try using ROW_NUMBER

something like

;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

نصائح أخرى

Try this,

;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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top