sql - 根据某列的值从不同行中选择值
问题描述
例如我有这样的数据
date | col_1 | Col_2 | Col_3 | Col_4
---------------------------------------------
20021 | 1 | a | null | a
20022 | 2 | a | null | a
20023 | 3 | a | null | a
20024 | 4 | a | 4.5 | a
20031 | 1 | a | 11 | b
20032 | 2 | a | 2 | b
20033 | 3 | a | 9 | b
20034 | 4 | a | 11 | b
我需要的是当 Col_3 中的值为 null 并且 Col_1 不是 4 时,然后选择 Col_3 中 Col_1 = 4 的值,它们具有相同的
我尝试使用这个案例陈述:
select col_2, date, col_1, col_4,
case when col_3 is null and col_1 != 1
then (select col_3 from table s where s.date = 4
and s.col_1= seg.col_1 and s.col_4= seg.col_4
and left(s.date,4) = left(seg.date,4))
else seg.col_3
end as col_3
from table seg
但由于某种原因,它没有做我需要它做的事情,我需要它来改变上表的结果,变成这样:
date | col_1 | Col_2 | Col_3 | Col_4
---------------------------------------------
20021 | 1 | a | 4.5 | a
20022 | 2 | a | 4.5 | a
20023 | 3 | a | 4.5 | a
20024 | 4 | a | 4.5 | a
20031 | 1 | a | 11 | b
20032 | 2 | a | 2 | b
20033 | 3 | a | 9 | b
20034 | 4 | a | 11 | b
解决方案
也许使用一个OUTER APPLY
(或者CROSS APPLY
如果你可以保证第 4 季度在那里)总是有每个 col4 每年可用的第 4 季度,然后在你必须的地方使用它。
select col_2, date, col_1, col_4,
case when col_3 is null and col_1 != 4
then backfill.col_3
else seg.col_3
end as col_3
from table seg
outer apply (select col_3 from table where col_1 = 4 and left(date,4) = left(seg.date,4)) and col_4 = seg.col_4) backfill
如果您宁愿坚持使用 CASE,这应该可以。
case when col_3 is null and col_1 != 4
then (select col_3 from table s where s.col_1 = 4
and s.col_4 = seg.col_4
and left(s.date,4) = left(seg.date,4))
else seg.col_3
推荐阅读
- javascript - 问题:更改 div 内容时出现 JS 错误
- python - 将列中的值除以列名的值
- flutter - 如何在 Flutter 中发出 POST 请求以发送 mp4 文件?(没有非核心 API)
- android - 当我在颤动中单击弹出按钮菜单中的项目时,如何转到另一条路线
- r - 如何动态创建具有整洁评估的列?
- c - 在 malloc 的返回值类型周围添加括号
- artifactory - Artifactory 和 Xray 可以使用通用的 RDS PostgreSQL 实例吗?
- mysql - mysql 安装损坏,导致 mysql 无法卸载
- javascript - 从 html 中的 app.js 调用函数时函数未定义和错误
- installation - 排查 Debian Preseed Late_command