0

我需要为每个 NEW DocNumber 增加一列(计数)+1。因此,如果三列的 DocNumber 相同,则计数器将为 1、2、3 等。下面是代码。我得到了它会更新整个表格的地步,只是不是基于相同或不同的文档编号。有人可以帮我解释这里的逻辑吗?

基本上,我想在计数器遇到新的 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
4

1 回答 1

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
于 2012-11-14T19:57:17.120 回答