sql - 根据行 SQL 的过去值添加计算字段
问题描述
我有一个包含日期字段和列“X”的数据集,如下所示。X 是一个二进制字段 - 我想在末尾添加一个字段(“所需字段(计算)”),它将为我提供字段“X”的 1 字符串开始的第一个日期。有任何想法吗?在 Excel 中,我会根据以下内容查看之前的行以检查它是否为空白:
逻辑:
Case when X=0 then Null when X=1 and 'desired field value for the row above' = Null, then Date when X=1 and 'desired field value for the row above' != Null, then value of 'desired field value for the row above' ) end as desired field
Date (dd/mm/yy)|X|desired field (calculated)
01/01/00 | |
02/01/00 |1|02/01/00
04/01/00 |1|02/01/00
10/01/00 |1|02/01/00
20/01/00 | |
20/02/00 | |
20/03/00 | |
04/04/00 |1|04/04/00
06/04/00 |1|04/04/00
10/04/00 |1|04/04/00
20/05/00 | |
解决方案
考虑以下方法
select * except(new_grp, grp),
case
when x = 1 then first_value(date) over(partition by grp order by cast(date as date format 'DD/MM/YY'))
else null
end desired_field
from (
select *, countif(new_grp) over(order by cast(date as date format 'DD/MM/YY')) grp
from (
select *, x != lag(x) over(order by cast(date as date format 'DD/MM/YY')) new_grp
from `project.dataset.table`
)
)
# order by cast(date as date format 'DD/MM/YY')
如果应用于样本数据 - 输出是
推荐阅读
- ruby - 使用 ruby on rails 测试 kaminari 参数是否存在
- python - Python:将表格输出数据导出到 csv 文件中
- javascript - 如何通过将 createImageThumbnails 设置为 false 在 Dropzone JS 中获取图像尺寸?
- python - 如何使用 boto3 cloudformation 资源列出和过滤堆栈?
- mysql - 在 MYSQL 中从组中查找最新行
- azure-devops - 如何允许客户仅读取 VSTS/Azure DevOps 中的特定分支
- c# - 从 Controller .Net Core 2.1 调用 Signalr 方法
- java - JAX-RS(Genson + jersey):对象未转换为 json
- python - 有人可以帮我吗?(Python 3)
- ios - JSONSerialization.jsonObject 返回 nil