sql - 基于分区添加列 - Oracle
问题描述
桌子:
Col1 Col2 Col3
43 1234 abc
42 1234 abc
41 1234 abc
35 1234 abc
34 5678 def
目标是根据以下内容创建一个Col4
1 或 0 的新列:
在每个分区内使用 with Col2 and Col3
,
要么
- 如果 Col1-1 不存在(或)
- 如果 Col1-1(和)Col1-2 两个值都存在于表中,
则 Col4 为 1,否则为 0。
输出表:
Col1 Col2 Col3 Col4
43 1234 abc 1
42 1234 abc 0
41 1234 abc 1
35 1234 abc 1
34 5678 def 1
解决方案
如果我遵循您描述的逻辑:
select t.*,
(case when lag(col1) over (partition by col2, col3 order by col1) <> col1 - 1
then 1
when lag(col1) over (partition by col2, col3 order by col1) is null
then 1
when lag(col1, 2) over (partition by col2, col3 order by col1) = col1 - 2
then 1
else 0
end) as col4
from t;
这是一个 db<>fiddle。
推荐阅读
- node.js - 将express + typescript部署到heroku时找不到模块
- jquery - ajax查询结果成功调用多次
- ios - TypeError:无法读取未定义的属性“参数”(第 3 行,文件“代码”)
- javascript - 使用 jQuery 在鼠标悬停时显示图像
- javascript - 如何更改图像源?
- python - TypeError at '' __init__() got an unexpected keyword argument ''
- amazon-web-services - DynamoDB Serverless 如何在幕后工作?
- spring-boot - Microsoft Azure 中的重定向 URL 将永远登录。我怎样才能改变它?
- python - sqlalchemy:如何增量更新 TEXT 或 VARCHAR 类型的行值?
- ruby-on-rails - ActiveAdmin 范围按钮方向和样式