0

I have table called Products. Let say this is my table,

ID    Name     ParentID
--    ---       --------
1      a        NULL
2      b        NULL
3      a1       1
4      a2       1
5      b2       2
6      b2       2

Now I need to add [Order] Column with respect to ParentID,

ID    Name     ParentID    Order
--    ---       --------   ----
1      a        NULL        NULL
2      b        NULL        NULL
3      a1       1            1
4      a2       1            2   
5      b2       2            1  
6      b2       2            2  

Creating [Order] is trivial but inserting record is a bit tricky part

Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

1 Answers1

3
UPDATE  [Products]
SET  [Products].[Order] = PTT.[Order]
FROM
    [Products]
    INNER JOIN (SELECT ID, ROW_NUMBER() OVER (PARTITION BY PT.ParentID ORDER BY ID) AS [Order]
                FROM [Products] PT
                WHERE PT.ParentID IS NOT NULL) AS PTT ON PTT.ID = [Products].ID
bjnr
  • 3,353
  • 1
  • 18
  • 32
  • 1
    Thank you Thank you. Just update your anser to, UPDATE [Products] SET [Products].[Order] = PTT.[Order] FROM [Products] INNER JOIN (SELECT ID, ROW_NUMBER() OVER (PARTITION BY PT.ParentID ORDER BY Name) AS [Order] FROM [Products] PT WHERE PT.ParentID IS NOT NULL) AS PTT ON PTT.ID = [Products].ID – Imran Qadir Baksh - Baloch Dec 19 '13 at 09:37
  • 1
    [You don't need a self join here](http://stackoverflow.com/questions/3439110/sql-server-update-a-table-by-using-order-by/3439180#3439180) – Martin Smith Dec 19 '13 at 11:09
  • @user960567 - It's SQL Hint's answer. I'll leave it up to them if they want to remove the unnecessary join. – Martin Smith Dec 19 '13 at 12:07