BigQuery SQL,基于配额值的汇总
问题:
所以我有一张包含产品配额批次的表。对于1个产品,它将具有几个quota_id,每个Quota_id具有不同的配额值。请在CTE 配额
中找到此表- 然后我有一张购买表,需要与配额表连接并进行汇总。汇总购买以填充第一个批次(第一个是用较早的批次_date批量的),然后在配额已满时移至第二批次。请参阅CTE 购买
SQL:
WITH quota AS (
select 'Product A' as product, 'Quota_batch_1' as quota_id, 10 as quota, '2022-01-01' as batch_date
UNION All
select 'Product A' as product, 'Quota_batch_2' as quota_id, 20 as quota, '2022-02-01' as batch_date
),
purchase as (
select '2022-01-01' as sales_date, 5 as qty, 'sales_1' as sales_id, 'Product A' as product, 100 as price
UNION ALL
select '2022-01-01' as sales_date, 5 as qty, 'sales_2' as sales_id, 'Product A' as product, 150 as price
UNION ALL
select '2022-02-03' as sales_date, 2 as qty, 'sales_3' as sales_id, 'Product A' as product, 200 as price
)
select
quota.*,
sum(qty) as quota_filled_by_qty,
sum(price) as total_price
from quota
left join purchase using (product)
group by 1,2,3,4
我不知道执行加入或聚合,因为我当前的结果仍在汇总为所有结果。我已经探索了使用分析功能,累积总和等,但仍然无法解决问题。
有什么想法吗?谢谢
Problem :
So I have a table containing quota batch of a product. For 1 product, it will have several quota_id with each quota_id has different value of quota. Please find this table in CTE quota
Then I have a table of purchase, which need to be joined with quota table and aggregate it. The purchase is aggregated to fill the first batch(the first is batch with earlier batch_date), then moved to second batch when the quota is full. Refer to CTE purchase
SQL :
WITH quota AS (
select 'Product A' as product, 'Quota_batch_1' as quota_id, 10 as quota, '2022-01-01' as batch_date
UNION All
select 'Product A' as product, 'Quota_batch_2' as quota_id, 20 as quota, '2022-02-01' as batch_date
),
purchase as (
select '2022-01-01' as sales_date, 5 as qty, 'sales_1' as sales_id, 'Product A' as product, 100 as price
UNION ALL
select '2022-01-01' as sales_date, 5 as qty, 'sales_2' as sales_id, 'Product A' as product, 150 as price
UNION ALL
select '2022-02-03' as sales_date, 2 as qty, 'sales_3' as sales_id, 'Product A' as product, 200 as price
)
select
quota.*,
sum(qty) as quota_filled_by_qty,
sum(price) as total_price
from quota
left join purchase using (product)
group by 1,2,3,4
I have no idea to do the join or the aggregation, as my current result is still aggregated for all result. I've explored like using analytical function, cumulative sum etc but still unable to crack the problem.
Any idea? thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 /a>并调整您的
JOIN
条件:输出:
An approach using
LEAD
navigation function and adjusting yourJOIN
condition:Output: