首页 > 解决方案 > 选择第二行值出现,覆盖第一行值

问题描述

S.No   Name     Organization    
 1     Jhon       XXXx    
 2                zzzz

我想要作为 zzzz 的 John 组织的结果

在选择针对“Jhon”的表时,我希望组织表返回值应该是 ZZZZ。我应该覆盖旧组织。

标签: sqlsql-servermysqli

解决方案


drop table t
go
create table t (id int, name varchar(10), organisation varchar(10))
go
truncate table t
insert into t values
(1,'n1','o1'),(2,null,'o2'),(3, null, 'o3'),(4,'n2','o4'),(5,null,'o5')

要用前一个非空名称覆盖空名称,然后使用相关子查询查找前一个名称,如下所示

select t.id,
(select t2.name from t t2 where t2.name is not null and t2.id = (select max(id) from t t3 where t3.name is not null and t3.id < t.id)) name, 
t.organisation 
from t
where name is null

result
id          name       organisation
----------- ---------- ------------
2           n1         o2
3           n1         o3
5           n2         o5

(3 row(s) affected)

反过来寻找下一个组织

select t.id,t.name,
(select t2.organisation from t t2 where t2.name is null and t2.id = (select min(id) from t t3 where t3.name is null and t3.id > t.id)) organisation 
from t
where name is not null

Result
id          name       organisation
----------- ---------- ------------
1           n1         o2
4           n2         o5

(2 row(s) affected)

两种结果都符合您的要求(当然完全不同)


推荐阅读