使用计数器增加列号

时间:2012-11-14 19:52:22

标签: sql-server counter

我需要为每个新DocNumber增加一列(Counts)+1。因此,如果三列的DocNumber相同,则计数器将为1,2,3等。以下是代码。我得到它将更新整个表,只是不基于相同或不同的docnumber。有人可以帮助我解决逻辑吗?

基本上,我想在点击新的TempDocNumber

时重新启动计数器
DECLARE @DocTable Table (DetailID FLOAT, TempDocNumber FLOAT, Counts INT)
INSERT INTO @DocTable (DetailID, TempDocNumber, Counts)
SELECT DetailID, DocumentNumber, 0 FROM ChargebackDetailTempTable


declare @Counter int
Set @Counter = 0
Update @Doctable
SET @Counter = counts = @Counter + 1

-- start counter over when new tempdocnumber

1 个答案:

答案 0 :(得分:3)

您可以像这样创建插入内容:

DECLARE @DocTable Table (DetailID FLOAT, TempDocNumber FLOAT, Counts INT)
INSERT INTO @DocTable (DetailID, TempDocNumber, Counts)
SELECT  DetailID, 
        DocumentNumber TempDocNumber, 
        ROW_NUMBER() OVER(PARTITION BY DocumentNumber ORDER BY DetailId) Counts
FROM ChargebackDetailTempTable

不需要UPDATE

对于SQL Server 2000

假设DetailID是一个标识列,您可以尝试以下操作(同样,不需要UPDATE):

DECLARE @DocTable Table (DetailID FLOAT, TempDocNumber FLOAT, Counts INT)
INSERT INTO @DocTable (DetailID, TempDocNumber, Counts)
SELECT  DetailID, 
        TempDocNumber,
        Counts = (  SELECT COUNT(T1.DetailID) + 1
                    FROM ChargebackDetailTempTable T1
                    WHERE T1.DetailID < T.DetailID and T1.TempDocNumber = T.TempDocNumber)
FROM ChargebackDetailTempTable T