从每日表构建每月汇总

时间:2018-05-17 20:31:28

标签: sql aggregate teradata vertica

我已编写以下代码,以检查过去30天内的独特客户。我如何重新使用此代码来检查一个月开始日期的唯一客户。我正在尝试使用具有每日谷物的table_billing构建每月聚合。你能指导我吗?

select 'context.processingDate' as rptg_dt, COALESCE(item_type,'ALL_ITEMS') as item_type, unique_customers
from (select 
        (case when item_type_code in ('A') then 'Books'
         when item_type_code in ('B','C') then 'Toys'
         else 'Fruits' end
         ) as item_type,
        count(distinct person_id) as unique_customers
      from table_billing
      where rptg_dt between cast('context.processingDate' as date format 'YYYY-MM-DD')-30 
        AND cast('context.processingDate' as date format 'YYYY-MM-DD')
        and item_type_code in ('A','B','C','D','E')
      group by CUBE(1)
    ) a;

期望的输出:

Monthly Start Date    | Item Type     | Unique Customers

5/1/14                | Books            | 100

5/1/14                | Toys             | 80

5/1/14                | Fruits           | 25

5/1/14                | ALL_ITEMS        | 175

6/1/14                | Books            | 80

6/1/14                | Toys             | 60

6/1/14                | Fruits           | 40

6/1/14                | ALL_ITEMS        | 95

我希望重新编写此查询,如下所示:

select 'context.processingDate' as month_start_dt, 
COALESCE(item_type,'ALL_ITEMS') as item_type, unique_customers
from (select 
(case when item_type_code in ('A') then 'Books'
when item_type_code in ('B','C') then 'Toys'
else 'Fruits' end
) as item_type,
count(distinct person_id) as unique_customers
from table_billing
where month_start_dt = cast('context.processingDate' as date format'YYYY-MM-DD') and item_type_code in ('A','B','C','D','E') group by CUBE(1)) a;

我如何调整查询以使其成为可能?谢谢!

0 个答案:

没有答案