根据多字符串SQL Server

时间:2016-02-29 23:03:17

标签: sql sql-server sql-server-2014

我的SQL Server数据库中有一个这样的表,唯一的区别是名称,我有大约200万行的NULL值。

enter image description here

我需要使用正确的名称更新公司名称。如果在具有公司名称的另一行中找到地址和邮政编码,如何编写将插入公司名称的查询?

这样我可以使用address =' address3'更新所有行。和zipcode =' 3333'到公司3'。唯一的问题是我有500家不同的公司,所以每个公司名称的手动更新都将永远! :)

是否需要遍历缺少公司名称的每一行,然后在同一个表中搜索该特定行的地址和邮政编码,如果匹配则需要使用公司列的值更新匹配的行? :d

1 个答案:

答案 0 :(得分:1)

在"标准"中执行此操作的一种方法SQL是一个相关的子查询:

update t
    set company = (select max(t2.company)
                   from t t2
                   where t2.company is not null and
                         t2.address = t.address and
                         t2.zipcode = t.zipcode -- and perhaps country as well
                  )
    where company is null;

根据您的数据库,可能还有其他方式来表达此查询。

注意:如果同一地址有多家公司,那么它会选择一个任意一个(好吧,不是任意的,按字典顺序排列名称最多的那个)。

编辑:

在SQL Server中,您可以使用join来编写此代码。但是,我喜欢使用窗口函数的想法:

with toupdate as (
      select t.*,
             max(company) over (partition by address, zipcode) as thecompany
      from t
     )
update toupdate
    set company = thecompany
    where company is null;