我正在尝试在sql查询中实现一些逻辑来创建一个类似于:
的表CountNum Identifier
20 a
40 a
60 a
20 b
40 b
20 c
20 d
40 d
20 e
40 e
60 e
80 e
正如您所看到的,逻辑是这样的,只要Identifer保持不变,CountNum就会向下一条记录添加20。如果标识符发生变化,则从20开始。
到目前为止,我已经实现了以下伪代码:
Do the following for all records:
Update table set CountNum=20 for first Identifier
If Identifier is duplicated, add 20 to CountNum for each duplicate.
无论如何,是否在SQL服务器中实现此查询?
我也试图将结果移到新表中。我试过了:
INSERT INTO tblPayments select Identifier AS PaymentsIdentifier
ROW_NUMBER() OVER(PARTITION BY Identifier ORDER BY Identifier)*20 CountNum
FROM dbo.oldPayments
然而,它会产生错误:
Column name or number of supplied values does not match table definition.
答案 0 :(得分:5)
根本不需要循环,您可以使用ROW_NUMBER()
:
SELECT Identifier,
ROW_NUMBER() OVER(PARTITION BY Identifier ORDER BY Identifier)*20 CountNum
FROM dbo.YourTable;