sql - 在 BigQuery 中计算订单序列
问题描述
我是 BigQuery SQL 的新手,正在努力从客户订单表中计算“订单序列”。
在我的示例中,我正在处理客户采购,其中我有销售渠道、唯一订单号、订单日期和其他采购以及客户信息。我还在查询中加入了两个表,以将所有必要的数据放入一个表中。
这是我当前查询的样子:
SELECT
t1.channel as sales_channel,
t1.number as order_number,
t1.date as order_date,
t1.email as customer,
t1.price as gross_price,
t1.sku as SKU,
t1.quantity as sku_quantity,
t1.sku_price as sku_price,
t2.order_status,
t2.weight,
t2.size
FROM order_itemsinfo t1
JOIN order_statusinfo t2
ON t1.number= t2.number
where t1.price > 0 AND
t1.sku in ("ABC-233-20L","DEF-100-10Y")
但是,基于此查询,我还想添加另一列“订单序列”,该列是根据客户级别并基于购买日期计算的。
因此,计算出的订单序列的结果应如下所示:
sales_channel | order_number | order_date | customer | ... | order_sequence
US | US184746 | 2020-01-04 | customer1@sample.com | ... | 1
US | US752646 | 2020-02-14 | customer1@sample.com | ... | 2
US | US975246 | 2020-02-28 | customer1@sample.com | ... | 3
US | US997512 | 2020-05-07 | customer1@sample.com | ... | 4
FR | FR210000 | 2020-03-22 | customer2@sample.com | ... | 1
FR | FR354884 | 2020-04-10 | customer2@sample.com | ... | 2
FR | FR578410 | 2020-04-30 | customer2@sample.com | ... | 3
UK | UK454100 | 2020-04-01 | customer3@sample.com | ... | 1
UK | UK884212 | 2020-08-21 | customer3@sample.com | ... | 2
IT | IT898990 | 2020-08-04 | customer4@sample.com | ... | 1
IT | IT999181 | 2020-10-24 | customer4@sample.com | ... | 2
IT | IT999652 | 2020-11-06 | customer4@sample.com | ... | 3
在不干扰 JOIN 和我的过滤器的情况下,如何最好地将其集成到上面的查询中?
谢谢!
解决方案
如果我理解正确,您将使用窗口函数:
SELECT . . .,
ROW_NUMBER() OVER (PARTITION BY ii.customer ORDER BY ii.date) as seqnum
FROM order_itemsinfo ii JOIN
order_statusinfo si
ON ii.number = si.number
WHERE ii.price > 0 AND
ii.sku in ('ABC-233-20L', 'DEF-100-10Y');
请注意,我更改了表别名。这些是表名的缩写,而不是使用无意义的字母。这使得查询更容易理解。
推荐阅读
- php - Laravel - 在 bool 上调用成员函数 categorie()
- android - 不能触发超过 1 个地理围栏通知
- python - TypeError:预期的 str、字节或 os.PathLike 对象,而不是 os.path.basename 的元组
- mysql - 重置 SQL 客户表中的数字
- css - 提取组件时的 Tailwind @apply 指令与纯 CSS
- html - Web 提取时出现 Pythonerror:AttributeError:“NoneType”对象没有属性“find_all”
- angularjs - 如何在打字稿中定义自定义地图类型?
- sql-server - vb.net插入语句:sql错误将数据类型varchar转换为数字
- python - MatplotLib 仅在内部的顶部和右侧轴上移动刻度
- typescript - 在子类型中使用索引中的类型