首页 > 解决方案 > 如何根据前一行有条件地插入一行?

问题描述

我目前正在尝试弄清楚如何根据前一行有条件地插入一行。我相当习惯于使用窗口函数,我认为我必须这样做才能使这项工作,但我不知道任何其他功能可以使这项工作。

我正在使用的数据集看起来像这样

原始表

我希望它看起来像这样:

修改后

因此,实际上,我希望添加两个行日期之间存在的差距。如果一行的结束日期与下一行的开始日期之间存在差距,我希望能够在它们之间插入具有相同项目的行并存储中间日期和销售金额0。_

我正在尝试在 Google BigQuery 控制台中执行此操作。

标签: sqlgoogle-bigquerysql-insertwhere-clausewindow-functions

解决方案


您可以使用union alllead()

select item, store, start, end, sold
from t
union all
select item, store, dateadd(end, interval 1 day), dateadd(next_start, interval -1 day)
from (select item, store, end, lead(start) over (partition item, store start) as next_start
      from t
     ) t
where next_start  dateadd(end, interval 1 day);

推荐阅读