【问题标题】:How to remove NULL values from two rows in a table如何从表中的两行中删除 NULL 值
【发布时间】:2021-09-06 02:13:46
【问题描述】:

我得到的输出是这个。

2015-10-01 NULL
NULL NULL
NULL NULL
NULL 2015-10-05
2015-10-11 NULL
NULL 2015-10-13
2015-10-15 2015-10-16
2015-10-25 NULL
NULL NULL
NULL NULL
NULL NULL
NULL NULL
NULL 2015-10-31

我想要这个

2015-10-01  2015-10-05
2015-10-11  2015-10-13
2015-10-15  2015-10-16
2015-10-25  2015-10-31 

我的代码:

select (case when (end_lag <> start_date) or end_lag is null then start_date end) as start_date, 
       (case when (start_lead <> end_date) or start_lead is null then end_date end) as end_date
from
    (select lead(start_date) over(order by start_date) as start_lead, start_date, end_date,                     lag(end_date) over(order by end_date) as end_lag
    from projects) t1;

原始表有两个属性(start_date,end_date),我为start_date创建了lead列,为end_date创建了lag列

【问题讨论】:

标签: sql oracle-sql-data-modeler targetnullvalue


【解决方案1】:

从当前的结果表中可以看到:

select start_date, end_date
from (select row_number() over(order by null) rn, start_date
      from current_t
      where start_date is not null) a
join (select row_number() over(order by null) rn, end_date
      from current_t
      where end_date is not null) b
on b.rn = a.rn;

(sql 小提琴here)

【讨论】:

    【解决方案2】:

    您的行似乎没有排序。因此,您可以取消旋转并将它们配对:

    select min(dte), nullif(max(dte), min(dte))
    from (select x.dte, row_number() over (order by dte) as seqnum
          from projects p cross join lateral
               (select p.start_date as dte from dual union all
                select p.end_date from dual
               ) x
         ) p
    group by ceil(seqnum / 2)
    

    【讨论】:

      【解决方案3】:

      忽略两个 NULL 并从原始查询中获取前导值。我想它可以被简化,如果没有 DDL 和样本数据就很难知道。

      select *
      from (
         select start_date, 
                case when end_date is null then lead(end_date) over(order by coalesce(start_date, end_date)) else end_date end end_date
         from (
            select * 
            from (
                 -- your original query
                 select (case when (end_lag <> start_date) or end_lag is null then start_date end) as start_date, 
                       (case when (start_lead <> end_date) or start_lead is null then end_date end) as end_date
                 from (
                   select lead(start_date) over(order by start_date) as start_lead, start_date, end_date,                     
                   lag(end_date) over(order by end_date) as end_lag
                   from projects) t1
                ---
           ) tbl
           where not (start_date is null and end_date is null )
         ) t
      ) t
      where start_date is not null
      order by start_date;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-05
        • 1970-01-01
        • 2016-08-28
        • 2017-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多