sql - 选择第二行值出现,覆盖第一行值
问题描述
S.No Name Organization
1 Jhon XXXx
2 zzzz
我想要作为 zzzz 的 John 组织的结果
在选择针对“Jhon”的表时,我希望组织表返回值应该是 ZZZZ。我应该覆盖旧组织。
解决方案
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)
两种结果都符合您的要求(当然完全不同)
推荐阅读
- image - Xamarin 图像数据在流副本上无效
- sql - SQL Server 中的转换函数
- apache-spark - 如何通过 Spark 将用户定义的元数据添加到 S3 对象
- winapi - Win16 应用程序的清单文件
- sql - 如何将where子句中的值与ID的最大值进行比较?
- java - 编辑:如何发送带有参数和表单数据的帖子请求,如 JAVA 中的邮递员截图?
- python - 使用 pandas 中其他两列的值从分类变量中创建列
- rust - 我的 Rust 代码比等效的 Python 代码长得多,结果错误
- webpack - 无法让 webpack-hot-client 在文件更改时重新加载
- android - Android Widget 显示错误和 updateAppWidget 找不到任何视图