google-cloud-platform - 数据变化时查询
问题描述
我有一张包含一年中每一天的产品、成本和日期的表格,例如
prod1, 1, 01/01/2020
prod1, 1, 02/01/2020
prod1, 2, 03/01/2020
prod1, 2, 04/01/2020
prod1, 1, 05/01/2020
prod1, 1, 06/01/2020
我如何生成一个查询来为我生产产品、成本和日期,每个产品都按顺序出现在每次更改的第一个和最后一个,即不是
prod1, 1, 01/01/2020 first, 06/01/2020 last
prod1, 2, 03/01/2020 first, 04/01/2020 last
但
prod1, 1, 01/01/2020 first, 01/01/2020 last
prod1, 2, 02/01/2020 first, 04/01/2020 last
prod1, 1, 05/01/2020 first, 06/01/2020 last
我知道这一定与 OVER 子句有关,但我正在为它对我的工作方式而苦苦挣扎
注意有多种产品
非常感谢任何帮助
解决方案
以下是 BigQuery 标准 SQL
#standardSQL
select product, cost, min(date) first_date, max(date) last_date
from (
select product, cost, date,
countif(cost_changed) over(partition by product order by date) grp
from (
select product, cost, date,
cost != lag(cost) over(partition by product order by date) cost_changed
from `project.dataset.table`
)
)
group by product, cost, grp
如果应用于您问题的样本数据 - 输出是
您可以使用下面的 CTE 测试、玩上面
with `project.dataset.table` as (
select 'prod1' as product, 1 as cost, DATE '2020-01-01' as date union all
select 'prod1', 1, '2020-01-02' union all
select 'prod1', 2, '2020-01-03' union all
select 'prod1', 2, '2020-01-04' union all
select 'prod1', 1, '2020-01-05' union all
select 'prod1', 1, '2020-01-06'
)
推荐阅读
- python - 通过 QueueHandler 进行 Python 多处理日志记录
- uml - PlantUML:彼此相邻的包,列表中的组件
- pandas - 数据框列的日期差异
- html - 3 张图片在使用 CSS 和 HTML 时未水平对齐
- mysql - 这是一对多的关系模型问题
- android - Arrow KT 上的依赖注入
- python - (python) 列表索引超出范围 - 使用 selenium click 事件
- java - 给定范围内的素数列表作为Java中的字符串
- java - 如何在 Spring 测试环境中反序列化 ClientResponse 主体?
- oracle - 无法使用 oracle db 在 golang 中构建应用程序