문제

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