1

I have the following data in a table:

Id      | InventoryId | RevisionId
-----------------------------------
1001    |   1234    |   1
1002    |   2235    |   1
1003    |   2235    |   2
1004    |   2235    |   2
1005    |   2235    |   3
1006    |   2235    |   4
1007    |   3234    |   1
1008    |   3234    |   2
1009    |   3234    |   3
1010    |   3234    |   3
1011    |   3234    |   4
1012    |   3234    |   5
1013    |   3234    |   5
1014    |   3234    |   6

I want to write a script which provide me data correction in following way

Id   |  InventoryId | RevisionId
---------------------------------
1001    |   1234    |   1
1002    |   2235    |   1
1003    |   2235    |   2
1004    |   2235    |   3
1005    |   2235    |   4
1006    |   2235    |   5
1007    |   3234    |   1
1008    |   3234    |   2
1009    |   3234    |   3
1010    |   3234    |   4
1011    |   3234    |   5
1012    |   3234    |   6
1013    |   3234    |   7
1014    |   3234    |   8

Can we do this with a SQL script?

Any suggestions?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ankit Vaidya
  • 35
  • 1
  • 8

4 Answers4

4

use row_number()

select *, row_number() over(partition by InventoryId order by id) as newRevisionId
from tablename 
Fahmi
  • 37,315
  • 5
  • 22
  • 31
2

Try this:

    DECLARE @Table TABLE(Id INT,InventoryId INT,RevisionId INT)

    INSERT INTO @Table
    SELECT 1001,1234,1 UNION ALL
    SELECT 1002,2235,1 UNION ALL
    SELECT 1003,2235,2 UNION ALL
    SELECT 1004,2235,2 UNION ALL
    SELECT 1005,2235,3 UNION ALL
    SELECT 1006,2235,4 UNION ALL
    SELECT 1007,3234,1 UNION ALL
    SELECT 1008,3234,2 UNION ALL
    SELECT 1009,3234,3 UNION ALL
    SELECT 1010,3234,3 UNION ALL
    SELECT 1011,3234,4 UNION ALL
    SELECT 1012,3234,5 UNION ALL
    SELECT 1013,3234,5 UNION ALL
    SELECT 1014,3234,6

    ;WITH cte
    AS(
        SELECT Id,InventoryId,RevisionId, ROW_NUMBER() OVER(PARTITION BY InventoryId ORDER BY id) AS NewRevision FROM @Table
      )
    UPDATE cte SET RevisionId=newRevision

    SELECT * FROM @Table
Sahi
  • 1,454
  • 1
  • 13
  • 32
2

If you want to update the values back to the table with new RevisionId, you can use CTE like following.

;with cte as
(
 select *, row_number() over(partition by InventoryId order by id) as rn
 from @table 
)

 update cte set RevisionId = rn
PSK
  • 17,547
  • 5
  • 32
  • 43
0

create table #temp1(A int,B int)

insert into #temp1(a,b)values (1001,1234) ,(1002,2235) ,(1003,2235) ,(1004,2235) ,(1005,2235) ,(1006,2235) ,(1007,3234) ,(1008,3234) ,(1009,3234) ,(1010,3234) ,(1011,3234) ,(1012,3234) ,(1013,3234) ,(1014,3234)

select *,row_number() over(partition by b order by b asc) from #temp1