基于SQL Server 2012中的行数更新行

基于SQL Server 2012中的行数更新行,sql,sql-server,sql-server-2012,cursor,sql-update,Sql,Sql Server,Sql Server 2012,Cursor,Sql Update,我收到了电子表格中的一些数据,这些数据很快就会自动导入,因此我无法在电子表格中进行任何手动输入。数据基本上有以下列。Trayid、trayname、itemdescription和rownumber。我没有自己构建这些表,或者我会以不同的方式构建,但我必须坚持已经设置好的格式 正在导入的数据将如下所示 Trayid | Trayname | ItemDescription | RowNumber 1 Tray 1 Product 1 1

我收到了电子表格中的一些数据,这些数据很快就会自动导入,因此我无法在电子表格中进行任何手动输入。数据基本上有以下列。Trayid、trayname、itemdescription和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
我猜我需要使用一个游标或其他东西,但我不确定,我认为可以通过向下移动行数并在再次看到行数1时停止,然后继续下一个trayid和trayname来完成


很抱歉,如果我所需要的东西没有意义,那么解释起来很尴尬。

SQL表没有固有的顺序。所以你不能相信这一点。但是,你可以做一些事情:

  • 在源表中定义
    标识
  • 在源表上创建排除标识的视图
  • 批量插入到视图中
这将按与原始数据相同的顺序为行分配序列号。让我们称之为
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;
其思想是定义与每个托盘对应的行组。简单的想法是在任何给定行之前计算非空值的数量——然后组中的所有内容都将具有相同的
grp
值。窗口函数然后将实际值分散到组中的所有行中(使用
max()
),这些值用于更新