2013-04-27 40 views
1

我有以下数据的表格,更新与现有表的字段自动递增逻辑

  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作为AutoIncrement。

+1

这是什么? – Freelancer 2013-04-27 04:57:43

+0

@Freelancer,我有一个现有的表。我想通过为每种产品类型自动递增来更新表格的订单列,如1,2,3 ...... – user960567 2013-04-27 05:01:23

+0

而不是1,2,1,2想要的订单列为1,2,3, 4 ???? – Freelancer 2013-04-27 05:07:36

回答

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); 
+0

优秀和不错 – user960567 2013-04-27 05:42:05

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 
+0

真棒........ ..... – 2013-04-27 05:13:05

+0

谢谢@mhasan ... – 2013-04-27 05:14:39

+0

获取错误,http://sqlfiddle.com/#!3/ddc04/1 – user960567 2013-04-27 05:17:37