UPDATE列基于分组中是否包含NULL

时间:2019-06-26 20:35:24

标签: sql sql-server tsql

这可能是一个非常简单的问题,但是我无法提出解决方案。

这里是一个示例

create table #Example
( 
    Key1 varchar(55) PRIMARY KEY,
    Key2 varchar(55),
    Key3 varchar(55),
    Key4 varchar(55)
)

insert into #Example
    select '1001', '100', NULL, NULL
    union all
    select '1002', '100', NULL, NULL
    union all
    select '1003', '200', NULL, NULL

Key1是唯一的。我们使用以下逻辑设置Key3:

with UpdateKey3 as
(
    select 
        Key1, Key2,
        ROW_NUMBER() OVER (PARTITION BY Key2 ORDER BY Key1 DESC) as RN
    from 
        #Example
)
update ao
set Key3 = m.Key1
from #Example ao
inner join UpdateKey3 m ON ao.Key2 = m.Key2
where m.RN = 1

表看起来像这样

enter image description here

我希望Key4是:

由于任何特定的Key3分组的Key4值都为NULL,请将其设置为Key3。结果应该是这个

enter image description here

现在,假设再增加1行:

insert into #Example
    select '1004', '100', NULL, NULL

然后我们运行UpdateKey3查询,结果将变为:

enter image description here

现在,我们需要****查询,这将更新Key4。由于新行位于Key3组= 1004中,并且我们之前已经为该组填充了Key4,因此NULL应该变为1002。最终结果

再说一次,一旦我们为任何特定的Key3分组设置了Key4,Key4就永远不会改变。那个****查询是什么?

enter image description here

1 个答案:

答案 0 :(得分:1)

很难理解,但是我想我明白你在说什么:

如果key4为空...

  • 尝试查找另一个具有相同key3值的记录,并查看其对key4的说明。
  • 如果任何这样的记录具有key4值,请使用它
  • 否则,只需使用当前记录的键3值

考虑到这一点,要更新密钥4,您可能需要这样的过程:

update    #Example
set       key4 = 
              isnull(
                  (
                      -- You have more than one row meeting your criteria.
                      -- Which do you choose.  I have a top 1, but order by what?
                      select 
                      top 1   key4 
                      from    #example sub 
                      where   #Example.key3 = sub.key3 
                      and     sub.key4 is not null
                  ), 
                  key3
              )
where     key4 is null

我强调“可能”是因为您的声明(我将其翻译成上面的第二个项目符号)

  

由于新行位于Key3组= 1004中,并且我们之前已经拥有   填充该组的Key4,NULL应该变成1002。

没有考虑两个先前存在的键3组1004可能具有不同的键4值的可能性。是的,在您的示例中,它们都是1002,但将来它们不会总是如此。

您将不得不在其中之一之间进行选择,并且不清楚该选择哪一个。在将任何此类代码投入生产之前,您确实必须对此加以确定。