繁体   English   中英

SQL Server-更新具有上一列的列而没有任何键

[英]SQL Server - Updating Columns with Previous column without Any Key

我有一个包含五列的SQL Server表:

Field1, Field2,Field3,Field4,Field5

现在,我从文件加载数据,该文件的第一行具有Field1Field2值,而第二行和第三行中只有field3field4field5

截至目前,我的表格中没有关键列。

我需要能够用第一行的值更新第二和第三行的field1field2

对于没有Field1Field2每一行,对于前一行,都需要重复此操作。

请提出一个可行的选择。

您只需要一把钥匙,就没有办法了。 SQL表未排序,因此您需要引入一个排序字段。 听起来好像您正在处理文本文件...如果这样,则需要添加一个整数,以便可以对记录进行排序。

然后,您可以结合使用合并函数(返回第一个非空值)和滞后函数,例如:

;with cte as (

    select  
         ID
        ,coalesce(
             f1
            ,lag(f1, 1) over (order by id)
            ,lag(f1, 2) over (order by id)
         ) f1
        ,coalesce(
             f2
            ,lag(f2, 1) over (order by id)
            ,lag(f2, 2) over (order by id)
         ) f2
        ,f3
        ,f4
        ,f5
        from (
            values
             (1, 'a1', 'b1', null, null, null)
            ,(2, null, null, 'x1', 'y1', 'z1')
            ,(3, null, null, 'l1', 'm1', 'n1')
            ,(4, 'a2', 'b2', null, null, null)
            ,(5, null, null, 'x2', 'y2', 'z2')
            ,(6, null, null, 'l2', 'm2', 'n2')
        ) t(ID, f1, f2, f3, f4, f5)
)
select *
    from cte
    where f3 is not null

这将返回一个数据表,例如:

2   a1  b1  x1  y1  z1
3   a1  b1  l1  m1  n1
5   a2  b2  x2  y2  z2
6   a2  b2  l2  m2  n2

另一种速度较慢的解决方案涉及相关子查询。 您的示例是一个父行,然后是两个子行,重复进行。 无论父行之间有多少子行,这都将起作用:

drop table if exists #temp
go

select *
    into #temp
    from (
        values
         (1, 'a1', 'b1', null, null, null)
        ,(2, null, null, 'x1', 'y1', 'z1')
        ,(3, null, null, 'l1', 'm1', 'n1')
        ,(4, null, null, 'i1', 'j1', 'k1')
        ,(5, 'a2', 'b2', null, null, null)
        ,(6, null, null, 'x2', 'y2', 'z2')
        ,(7, null, null, 'l2', 'm2', 'n2')
    ) t(ID, f1, f2, f3, f4, f5)

update #temp
    set 
         f1 = (select top 1 f1 from #temp where f1 is not null and t.ID>=ID order by ID)
        ,f2 = (select top 1 f2 from #temp where f2 is not null and t.ID>=ID order by ID)
    from #temp t

select *
    from #temp
    where f3 is not null
    order by ID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM