2014-03-26 26 views
-1

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

我想我没有解释得这么好。不知道RowNumber函数我试图做一次一个光标去遍历一个记录,但它并不真正为我工作,所以我想我会问是否有人知道一个更简单的方法。我不知道如何通过这三个字段,po p0line和项目正确地进行修改。然后我也搜索了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条记录可以一起完成。

+3

这个问题似乎是题外话,因为没有尝试所示 –

+0

对不起,我还以为我被描述。但我看到吃桃子让我迷上了它,并使它看起来更好。我需要了解如何在我看到的格式中设置文章格式。感谢您的输入。 – morgaad1

回答

1

您可以使用row_number()

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

编辑:上述不起作用,因为“窗函数只能出现在SELECT或ORDER BY子句”。

要解决该问题,可以使用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 
+0

我试过了,它给了我一个错误。 “窗口函数只能出现在SELECT或ORDER BY子句中。”谢谢 – morgaad1

+0

啊耶,编辑。 – Blorgbeard

+0

我知道了使用this.Select po_num, po_line, ROW_NUMBER()以上(由po_num分区,由DUE_DATE po_line顺序)PO_release, 项, 描述, DUE_DATE 成common.dbo.PO_RELEASE 从共同.dbo.PO_releaseNumber – morgaad1