sql server语言 - T sql编号组的数据



我正试图找出如何在一个字段中插入序列号,用于匹配组,从3个其他字段。

我想我解释得不够好。不知道RowNumber函数,我试图做一个游标去通过记录一次一个,但它不是真的为我工作,所以我想我会问是否有人知道一个更简单的方法。我不确定如何正确地增加这3个字段,po - 0line和item。然后我又在StackOverflow上搜索了大约3个小时,没有找到任何与我的需求相似的东西。所以我把问题贴出来了。对于我想要做的事情,我有一个当前条件和目标条件的例子,所以我不知道该怎么说,因为你们有些人认为这不够描述。

    Declare @po_num nvarchar(10)
Declare @po_line int
Declare @po_release int
Declare @item nvarchar(30)
Declare @description nvarchar(40)
declare @due_date datetime
declare @CUR CURSOR 
SET @CUR = CURSOR LOCAL SCROLL STATIC
FOR
SELECT [po_num]
      ,[po_line]
      ,[po_release]
      ,[item]
  FROM [common].[dbo].[PO_ReleaseNumber] p
order by po_num, po_line
open @CUR
fetch NEXT from @CUR
into @po_num,@po_line,@po_release,@item
WHILE @@FETCH_STATUS = 0
BEGIN 
    update [common].[dbo].[PO_ReleaseNumber] set po_release = 1
where po_num = @po_num and po_line = @po_line and item = @item
    fetch NEXT from @CUR
    into @po_num,@po_line,@po_release,@item
    END

CLOSE @CUR
DEALLOCATE @CUR
GO

例句:这是我现在有的。

po_num  | po_line | Item   | due_date    | Sequence Num
-----------------------------------------------------------
999     | 1       | thing1 | 01/01/2014  |         
999     | 1       | thing1 | 01/15/2014  |     
999     | 1       | thing1 | 01/30/2014  |      
999     | 2       | thing2 | 01/01/2014  |        
999     | 3       | thing2 | 02/13/2014  |         
999     | 3       | thing2 | 03/13/2014  |        
999     | 3       | thing2 | 04/13/2014  |         
999     | 3       | thing2 | 04/15/2015  |   

这就是我想如何编号(sequenceNumber)或po_release号实际上。

po_num |  po_line| Item    | due_date    | Sequence Num
---------------------------------------------------------
999    |  1      | thing1  | 01/01/2014  | 1 
999    |  1      | thing1  | 01/15/2014  | 2
999    |  1      | thing1  | 01/30/2014  | 3
999    |  2      | thing2  | 01/01/2014  | 1
999    |  3      | thing2  | 02/13/2014  | 1
999    |  3      | thing2  | 03/13/2014  | 2
999    |  3      | thing2  | 04/13/2014  | 3
999    |  3      | thing2  | 04/15/2015  | 4

因此,该表实际上应该有相同PO_num、PO_Line、Item的每个版本的发布号,但发布日期不同,并且发布号缺失。现在我要给它们都编号。总共有75000条记录要检查

您可以使用row_number():

update [table]
set sequenceNumber = 
    row_number() over (partition by po_num, po_line, item order by due_date)

编辑:上面的不起作用,因为"窗口函数只能出现在SELECT或ORDER BY子句中"。

要解决这个问题,您可以在select中而不是在外部语句的set中使用窗口函数(row_number)连接到子查询。

类似这样的内容(同样,未经测试):

update t
set sequenceNumber = s.rownum
from [table] t
join (
    select po_num, po_line, item, due_date, 
    row_number() over 
        (partition by s.po_num, s.po_line, s.item 
         order by s.due_date) as rownum
) s on t.po_num=s.po_num and t.po_line=s.po_line and 
       t.item=s.item and t.due_date=s.due_date

最新更新