如何解决条件中的列创建-SQL
表格:
col1 col2 col3
236 1234 lion
236 1234
235 1023
235 1234
234 1234
232 1234
232 1234 tiger
231 1234
231 1234 cat
旨在创建col4并将if的值从col3复制到col4(如果在col2上进行分区):
col3中是否存在“ cat”,然后检查col1 + 5是否存在,如果是,则“ cat”行中col3的值转到该col4(其col1值为cat的“ col1 + 5”)
输出:
col1 col2 col3 col4
236 1234 lion
236 1234 cat
235 1023
235 1234
234 1234
232 1234
232 1234 tiger
231 1234
231 1234 cat
解决方法
如果我理解正确,则可以使用left join
:
select t.*,(case when t.col3 is null then t5.col3 end) as col4
from t left join
t t5
on t5.col1 = t.col1 + 5 and t5.col2 = t.col2 and t5.col3 = 'cat'
,
您的问题没有得到很好的描述,但是看起来正是您所需要的:
with t(col1,col2,col3) as (
select 236,1234,'lion' from dual union all
select 236,'' from dual union all
select 235,1023,'' from dual union all
select 234,'' from dual union all
select 232,'tiger' from dual union all
select 231,'' from dual union all
select 231,'cat' from dual
)
select
t.*,case
when col3 is null then
max(col3)over(partition by col2 order by col1 range between 5 preceding and 5 preceding)
end col4
from t
order by col1 desc,col2 asc,col3
/
结果:
COL1 COL2 COL3 COL4
---------- ---------- ----- -----
236 1234 lion
236 1234 cat
235 1023
235 1234
234 1234
232 1234 tiger
232 1234
231 1234 cat
231 1234
9 rows selected.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。