sql - 如何根据前一行有条件地插入一行?
问题描述
我目前正在尝试弄清楚如何根据前一行有条件地插入一行。我相当习惯于使用窗口函数,我认为我必须这样做才能使这项工作,但我不知道任何其他功能可以使这项工作。
我正在使用的数据集看起来像这样
我希望它看起来像这样:
因此,实际上,我希望添加两个行日期之间存在的差距。如果一行的结束日期与下一行的开始日期之间存在差距,我希望能够在它们之间插入具有相同项目的行并存储中间日期和销售金额0。_
我正在尝试在 Google BigQuery 控制台中执行此操作。
解决方案
您可以使用union all
和lead()
:
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);
推荐阅读
- python-3.x - python3中的tkSimpleDialog用法
- ios - 在本地网络上执行 GET 请求时出现错误 1009
- angular - 在页面重新加载时重新获取 Firestore 数据
- flutter - AnnotatedRegion 用于更改 statusBarColor
- html - 使用角度将视频从浏览器投射到 Chromecast
- ios - 开关中的多种类型案例
- javascript - 如何从数组中的今天日期获取最后六个月并在javascript中返回该数组
- c - 我如何生成 n 个子进程以同时运行,测量它们的执行时间并防止它们中的每一个超过最大执行时间?
- javascript - 如何恢复用户输入的输入值。知道输入是使用 *ngFor 指令动态创建的
- c++ - 运行程序后 Windows 控制台帧率下降