【问题标题】:Group by both users and month in Google BigQuery在 Google BigQuery 中按用户和月份分组
【发布时间】:2021-02-12 19:46:55
【问题描述】:

我是 BigQuery 的新手,我编写了以下查询:

select
email,
min(address.zip) as zip,
min(country) as country,
min(source),
min(created_at) as first_order,
max(created_at)as last_order,
count(order_number) as number_orders,
sum(total_price) as total_spent
from orders_data
group by email

它给我的是一个表格,其中所有订单都按客户分组,输出如下:

email | zip | country | source | first_order | last_order | number_orders | total_spent |

我想补充的是另一个按月分组。我希望每月获得每位客户(电子邮件)的 total_spend 和 number_orders。

根据更容易的情况,结果可能如下所示:

email | zip | country | source | first_order | last_order | number_orders | total_spent | 2017_January_spent | 2017_January_num_orders | 2017_February_spent | 2017_February_num_orders | ... | 

或按行分组,如下所示:

 month  | email | zip | country | source | first_order | last_order | number_orders | total_spent | 2017_January_spent | 2017_January_num_orders | 2017_February_spent | 2017_February_num orders | ... | 
 01.2017| cust_A|
 02.2017| cust_A|
 03.2017| cust_A|

不确定是否有帮助,但我的数据范围从 2017 年到 2020 年,我的时间戳变量“created_at”如下所示:2020-01-02 16:20:12 UTC

我已经尝试通过添加group by moth(created_at) 并且还使用timestamp_trunc 但失败了。

我们将不胜感激!

非常感谢!

【问题讨论】:

    标签: sql date group-by google-bigquery


    【解决方案1】:

    使用date_trunc() 或适合您的列类型的函数:

    select timestamp_trunc(created_at, month) as mon, email,
           min(address.zip) as zip, min(country) as country, min(source),
           min(created_at) as first_order, max(created_at)as last_order,
           count(order_number) as number_orders, sum(total_price) as total_spent
    from orders_data
    group by mon, email
    order by mon, email;
    

    【讨论】:

    • 嘿!感谢您的快速回复。我已经尝试过代码,但不幸的是它给了我以下错误:没有匹配的函数 DATE_TRUNC 参数类型的签名:TIMESTAMP,DATE_TIME_PART。支持的签名:DATE_TRUNC(DATE, DATE_TIME_PART) at [2:1] - 你知道问题可能是什么吗?
    • @emil_rore 。 . .那你要timestamp_trunc()
    猜你喜欢
    • 2018-08-10
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多