【问题标题】:column creation on condition - sql根据条件创建列 - sql
【发布时间】:2020-08-11 16:46:30
【问题描述】:

表:

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 并将值从 col3 复制到 col4 if(在 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

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    如果我理解正确,你可以使用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'
    

    【讨论】:

      【解决方案2】:

      您的问题没有很好地描述,但看起来这就是您所需要的:

      with t(col1,col2,col3) as (
          select  236 ,1234,'lion'  from dual union all
          select  236 ,1234,''      from dual union all
          select  235 ,1023,''      from dual union all
          select  235 ,1234,''      from dual union all
          select  234 ,1234,''      from dual union all
          select  232 ,1234,''      from dual union all
          select  232 ,1234,'tiger' from dual union all
          select  231 ,1234,''      from dual union all
          select  231 ,1234,'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.
      

      【讨论】:

        猜你喜欢
        • 2020-07-29
        • 1970-01-01
        • 1970-01-01
        • 2020-10-03
        • 2020-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多