首页 > 解决方案 > 在 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 和我的过滤器的情况下,如何最好地将其集成到上面的查询中?

谢谢!

标签: sqlgoogle-bigquerysql-order-bysequence

解决方案


如果我理解正确,您将使用窗口函数:

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');

请注意,我更改了表别名。这些是表名的缩写,而不是使用无意义的字母。这使得查询更容易理解。


推荐阅读