使用“自动递增逻辑”更新现有表的字段

时间:2013-04-27 04:55:34

标签: sql sql-server-2008

我有一张包含以下数据的表格,

          Product
-----------------------------
ID   Name ProductTypeID Order
1     A        1          0
2     B        1          0
3     D        2          0
4     C        2          0
-----------------------------------
-----------------------------------
-----------------------------------

我需要更新订单以使其值变为

          Product
-----------------------------
ID   Name ProductTypeID Order
1     A        1          1
2     B        1          2
3     D        2          1
4     C        2          2
-----------------------------------
-----------------------------------
-----------------------------------

看到它正在为每个ProductTypeID增加Order as AutoIncrement。

2 个答案:

答案 0 :(得分:4)

您要做的是获取分区内记录的排序。 query to do what you want is this

WITH sorted AS (
    SELECT id, ROW_NUMBER() OVER(PARTITION BY ProductTypeId ORDER BY id ASC) as rownum
    FROM product
)
UPDATE product
SET [order] = s.rownum
FROM product p
   INNER JOIN sorted s on (p.id = s.id);

答案 1 :(得分:2)

现在

 Update product  Set  [order]= Case  when Not Exists (Select * from
 product a where  a.ProductTypeID =product.ProductTypeID  and a.id
 <product.ID )
     tHEN 1
     eLSE 
     ((Select Count([ORDER]) from product  b where 
     b.ProductTypeID =product.ProductTypeID  and b.ID <product.id)+1)
    eND