T SQL数组数据

时间:2014-03-26 02:56:12

标签: sql sql-server tsql

我试图弄清楚如何在一个字段中插入一个序列号,用于匹配来自其他3个字段的组。

我想我没有解释这个问题。我没有意识到RowNumber函数,我试图用光标一次浏览一个记录,但它并不适合我,所以我想我会问是否有人知道更简单的方法。我不确定如何通过3个字段,po p0line和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,具有不同发布日期的项目的每个版本的版本号,并且缺少版本号。所以我现在必须对所有这些进行编号。共有大约75,000条记录可以通过。

1 个答案:

答案 0 :(得分:1)

您可以使用row_number()

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

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

要解决此问题,您可以使用select中的窗口函数(row_number)而不是外部语句的set加入子查询。

像这样(再次,未经测试):

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