我需要将一列的运行计数添加到第二个库中

时间:2019-06-28 14:36:08

标签: sql-server

嗨,我想将col1的运行计数添加到col2

std::sort

我有这个查询,确实可以给我一个连续的计数并将其放入ResItem

Col1     Col2
2        1
2        2
2        3
2        4
3        1
3        2
4        1
4        2
4        3
5        1
5        2

现在我只需要一种方法即可将ResItem的结果输入col2

1 个答案:

答案 0 :(得分:0)

您需要primary key到表中。这是SQL代码

首先让我们创建表

CREATE TABLE tblData1 (
    id int PRIMARY KEY NOT NULL IDENTITY(1, 1),
    Col1 int NOT NULL,
    Col2 int NULL
 );

 INSERT INTO tblData1 (Col1) VALUES (1);
 INSERT INTO tblData1 (Col1) VALUES (1);
 INSERT INTO tblData1 (Col1) VALUES (2);
 INSERT INTO tblData1 (Col1) VALUES (2);
 INSERT INTO tblData1 (Col1) VALUES (2);
 INSERT INTO tblData1 (Col1) VALUES (3);
 INSERT INTO tblData1 (Col1) VALUES (3);
 INSERT INTO tblData1 (Col1) VALUES (4);
 INSERT INTO tblData1 (Col1) VALUES (4);
 INSERT INTO tblData1 (Col1) VALUES (5);
 INSERT INTO tblData1 (Col1) VALUES (5);
 INSERT INTO tblData1 (Col1) VALUES (5);

这是您需要的UPDATE查询:

UPDATE tblData1
SET Col2 = cnt.aValue
FROM (
    SELECT 
        id, ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col1) AS aValue
    FROM
        tblData1
) cnt
WHERE tblData1.id = cnt.id

这是结果

enter image description here