2014-11-25 100 views
3

我已經在電子表格中給出了一些數據,這些數據很快將進入自動導入,因此我無法在電子表格中執行任何手動輸入。數據基本上有以下幾列。 Trayid,托盤名稱,itemdescription和rownumber。我自己沒有建立這些表或我會建立它不同,但我必須堅持已經設置的格式。根據SQL Server 2012中的rownumber更新行

正在導入的數據將在後面進行介紹。

Trayid | Trayname | ItemDescription | RowNumber 
1  Tray 1  Product 1   1 
        Product 2   2 
        Product 3   3 
        Product 4   4 
2  Tray 2  Product 1   1 
        Product 2   2 
        Product 3   3 
        Product 4   4 
        Product 5   5 

什麼,我需要做的是更新每個以下第1行的其他行的trayid和trayname,因此,例如它會看起來像。

Trayid | Trayname | ItemDescription | RowNumber 
1  Tray 1  Product 1   1 
1  Tray 1  Product 2   2 
1  Tray 1  Product 3   3 
1  Tray 1  Product 4   4 
2  Tray 2  Product 1   1 
2  Tray 2  Product 2   2 
2  Tray 2  Product 3   3 
2  Tray 2  Product 4   4 
2  Tray 2  Product 5   5 

即時猜測我需要使用光標或東西,但林不知道,我想它可以通過下降的rownumbers,當它看到的ROWNUMBER 1停止再次,然後下一個trayid繼承和完成trayname。

對不起,如果我需要沒有意義,它是尷尬的解釋。

回答

1

SQL表沒有固有的順序。所以你不能依賴那個。但是,您可以執行以下操作:

  • 在源表中定義一個identity列。
  • 在排除標識的源表上創建一個視圖。
  • 批量插入到視圖中。

這將按照與原始數據相同的順序爲行分配一個連續的數字。我們稱之爲id。然後,你可以做你做更新:

with toupdate (
     select t.*, 
      max(TrayId) over (partition by grp) as new_TrayId, 
      max(TrayName) over (partition by grp) as new_TrayName 
     from (select t.*, 
        count(TrayId) over (order by id) as grp 
      from t 
      ) t 
    ) 
update toupdate 
    set TrayId = new_TrayId, 
     TrayName = new_TrayName 
    where TrayId is null; 

的想法是定義對應於每個托盤組行。簡單的想法是計算任何給定行之前的非NULL值的數量 - 組中的所有數據將具有相同的grp值。窗口函數然後通過組中的所有行分散實際值(使用max()),並將這些值用於更新。