在同一 SELECT 查询中聚合多个日期粒度

问题描述 投票:0回答:1

我正在使用 Redshift,我想按不同的日期粒度计算客户数量:日、周、月。

我写了这个查询:

SELECT new_client,
       COUNT(DISTINCT clientId) number_clients,
       DATE_TRUNC('day', _date) AS date_day,
       DATE_TRUNC('month', _date) AS date_month
FROM   ClientsTable
GROUP BY new_client, date_day, date_month

这将返回以下结果格式:

new_client number_clients    date_day    date_month
   true         29          2023-06-01   2023-06-01
   false        135         2023-06-01   2023-06-01
   true         49          2023-06-02   2023-06-01
   false        151         2023-06-02   2023-06-01
   true         339         2023-06-03   2023-06-01
   false        97          2023-06-03   2023-06-01
   true         23          2023-06-04   2023-06-01
   false        10          2023-06-04   2023-06-01
   ...          ...           ...           ...

但是在这种情况下,如果我想要每月的值,我无法将每天的客户数量相加:因为同一个客户可以多天访问,在这种情况下我必须计算他一次。

我最想做的就是得到这样的结果:

new_client number_clients   date_day    date_month
   true         150          NULL        2023-06-01
   false        360          NULL        2023-06-01
   true         29          2023-06-01   2023-06-01
   false        135         2023-06-01   2023-06-01
   true         49          2023-06-02   2023-06-01
   false        151         2023-06-02   2023-06-01
   true         339         2023-06-03   2023-06-01
   false        97          2023-06-03   2023-06-01
   true         23          2023-06-04   2023-06-01
   false        10          2023-06-04   2023-06-01
   ...          ...           ...           ...

第一行汇总了整个月的值。

我尝试使用 WINDOW 函数来尽可能简单地完成此操作

SELECT new_client,
       COUNT(DISTINCT clientId) OVER(partition BY  DATE_TRUNC('day', _date) )  number_clients_day
FROM   ClientsTable 

我收到错误

[XX000]错误:不支持WINDOW定义

如有任何帮助,我们将不胜感激

sql amazon-redshift window-functions
1个回答
0
投票

由于您需要进行两个不同级别的聚合并希望结果按行排列,因此我们可能需要使用两个查询进行聚合,然后使用

union
来获取结果。

SELECT new_client,
       COUNT(DISTINCT client_Id) number_clients,
       DATE_TRUNC('day', _date)::text AS date_day,
       DATE_TRUNC('month', _date) AS date_month
FROM   ClientsTable
GROUP BY new_client, date_day, date_month
UNION ALL
SELECT new_client,
       COUNT(DISTINCT client_Id) number_clients,
       NULL as date_day,
       DATE_TRUNC('month', _date) AS date_month
FROM   ClientsTable
GROUP BY new_client, date_day, date_month
ORDER BY date_day ASC NULLS FIRST;

警告:如果您有大量数据,这可能效果不佳。

© www.soinside.com 2019 - 2024. All rights reserved.