计算每个客户的订单数

uhry853o  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(397)

我有一个包含以下列的表: date , customers_id ,和 orders_id (独一无二)。
我想添加一列,其中 order_id ,我可以看到给定的客户在上一年已经下了多少次订单。
e、 g.这就是它的样子:

customers_id | orders_id |    date     | order_rank
   2083      |   4725    | 2018-08-314 |     1
   2573      |   4773    | 2018-09-035 |     1
   3393      |   3776    | 2017-09-11  |     1
   3393      |   4172    | 2018-01-09  |     2
   3393      |   4655    | 2018-08-17  |     3

我在bigquery做这个,谢谢!

ewm0tg9j

ewm0tg9j1#

使用 count(*) 有窗框的。理想情况下,你会使用一个间隔。但是bigquery还不支持这种语法。所以转换成一个数字:

select t.*,
       count(*) over (partition by customer_id
                      order by unix_date(date)
                      range between 364 preceding and current row
                     ) as order_rank
from t;

这将一年视为365天,这似乎适用于大多数目的。

niwlg2el

niwlg2el2#

我建议你用 over 子句并限制 where 条款。你的案子不需要一个窗口。如果你考虑一个从过去的365天到现在的周期,这是可行的:

select t.*,
       count(*) over (partition by customer_id
                      order by date
                     ) as c
from `your-table` t
where date > DATE_SUB(CURRENT_DATE(), INTERVAL 365 DAY)
order by customer_id, c

如果您需要某个特定年份,例如2019年,您可以执行以下操作:

select t.*,
       count(*) over (partition by customer_id
                      order by date
                     ) as c
from `your-table` t
where date between cast("2019-01-01" as date) and cast("2019-12-31" as date)
order by customer_id, c

相关问题