0

我在数据库中有两个问题。一个是First name是缩写,另一个是zip code是null。我附上两个查询。第一个是我要修改的。第二个是所需的表。在第二个中,空 zip 被替换为最接近年份的 zip,缩写的 FirstName 被替换为他的完整名字。请注意,该表的行数约为 1000 万。转换后第一张和第二张表的行数应该相同。非常感谢。

----首先查询显示现有表内容----------

DROP table t11;

CREATE table t11(id int, lastname varchar(20), FirstName varchar(10), Year1 int, Zip int, purchase varchar(10));

insert into t11 values
    (1, 'Smith', 'Rick', 1996, 32203, 'tv')

,   (1, 'Smith', 'R.', 1998, 32205, 'laptop')

,   (1, 'Smith', 'Rick', 2000, null, 'LCD')

,   (2, 'Derek', 'J.', 1996, 42201, 'Food')

,   (2, 'Derek', 'Jeter', 1991, NULL, 'Egg')

SELECT top 1000 * FROM t11

----第二次查询显示所需的表格内容---------

DROP table t11;

CREATE table t11(id int, lastname varchar(20), FirstName varchar(10), Year1 int, Zip int, purchase varchar(10));

insert into t11 values

    (1, 'Smith', 'Rick', 1996, 32203, 'tv')

,   (1, 'Smith', 'Rick', 1998, 32205, 'laptop')

,   (1, 'Smith', 'Rick', 2000, 32205, 'LCD')

,   (2, 'Derek', 'Jeter', 1996, 42201, 'Food')

,   (2, 'Derek', 'Jeter', 1991, 42201, 'Egg')


SELECT top 1000  * FROM t11
4

1 回答 1

0

以下查询使用相关子查询表达了您想要的逻辑:

select t.id, t.LastName, 
       (select top 1 t2.FirstName
        from tt1 t2
        where t2.id = t.id
        order by len(t2.FirstName) desc
       ) as FirstName,
       (select top 1 t2.ZipCode
        from tt1 t2
        where t2.id = t.id and
              t2.year <= t.year and
              t2.ZipCode is not null
        order by t2.year desc
       ) as ZipCode,
       purchase
from t11 t;

您的问题不清楚您是要创建新表还是更新现有表。填写数据的策略取决于您在做什么。

编辑:(对于最近的邮政编码)

select t.id, t.LastName, 
       (select top 1 t2.FirstName
        from tt1 t2
        where t2.id = t.id
        order by len(FirstName) desc
       ) as FirstName,
       (select top 1 t2.ZipCode
        from tt1 t2
        where t2.id = t.id and
              t2.ZipCode is not null
        order by abs(t2.year - t.year)
       ) as ZipCode,
       purchase
from t11 t;
于 2013-07-26T00:46:02.333 回答