更新组MS SQL上的增量行号

时间:2017-04-18 19:49:43

标签: sql-server

CREATE TABLE PickSequence(
    [PickItemCode] [varchar](30) NOT NULL,
    [PickSequence] [numeric](18, 0) NULL,
)

INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695D-CV',1)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695D-CV',2)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695D-CV',3)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695D-CV',NULL)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695D-CV',NULL)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695D-CV',NULL)

INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695C-CV',NULL)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695C-CV',NULL)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695C-CV',NULL)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695C-CV',NULL)
INSERT INTO PickSequence (PickItemCode, PickSequence) VALUES ('695C-CV',NULL)

SELECT PickItemCode, PickSequence FROM PickSequence ORDER BY PickItemCode, PickSequence

| PickItemCode | PickSequence |
|:------------:|--------------|
| 695D-CV      | 1            |
| 695D-CV      | 2            |
| 695D-CV      | 3            |
| 695D-CV      | NULL         |
| 695D-CV      | NULL         |
| 695D-CV      | NULL         |
| 695C-CV      | NULL         |
| 695C-CV      | NULL         |
| 695C-CV      | NULL         |
| 695C-CV      | NULL         |
| 695C-CV      | NULL         |

我正在寻找下面的输出

| PickItemCode | PickSequence |
|:------------:|--------------|
| 695D-CV      | 1            |
| 695D-CV      | 2            |
| 695D-CV      | 3            |
| 695D-CV      | 4            |
| 695D-CV      | 5            |
| 695D-CV      | 6            |
| 695C-CV      | 1            |
| 695C-CV      | 2            |
| 695C-CV      | 3            |
| 695C-CV      | 4            |
| 695C-CV      | 5            |

使用下面的代码,我能够查询创建序列号的表格,但不知道如何让它看到该PartItemCode的最高值。

SELECT PickItemCode,
    PickSequence = ROW_NUMBER() OVER(PARTITION BY PickItemCode ORDER BY PickItemCode) ,
    [Part_Index] = DENSE_RANK() OVER (ORDER BY PickItemCode)
FROM PickSequence

我想要做的是使用PickItemCode分组的序列中的下一个数字更新PickSequence值。

1 个答案:

答案 0 :(得分:0)

UPDATE UpdateTarget 
SET PickSequence = NewSequence
FROM
(
    SELECT PickSequence,
    ROW_NUMBER() OVER(PARTITION BY PickItemCode ORDER BY CASE WHEN PickSequence IS NULL THEN 1 ELSE 0 END, PickSequence) as NewSequence
    FROM PickSequence
) as UpdateTarget