我仍在学习编写它,下面的查询没有给我准确的结果,而且它也没有优化。
因此,我要做的主要事情之一是创建3种日期类型:
在我的数据集中。
为此,我正在做一个工会。
所有3个数据集都在查询相同的源sales_main
。问题出在我的第二个数据集中,其中“退款”为date_type,由于ColumnA =“ B”条件,它没有提取实际行。
我希望此集合仅查看那些在第一个数据集中提取的记录(即“ Sales_shift”作为date_type),然后应用条件ColumnA =“ B”。我该怎么办?
我的以“ sales_reg”作为date_type的第三个数据集应与第一个数据集相同,但transaction_date不变。我怎么做。我在想哪里存在,但不知道如何应用。
任何帮助都会很棒。非常感谢
create table sales_refund as select * from (
with table1 as (select 'Sales_shift' as date_type,
add_months(date_trunc('month',transaction_date),1) as event_date,
sku,
sum(sales) as Sales_total,
sum(refund) as Refund_total,
case when region in ('US','EU') then 'type A' else 'type B' end as Flag_field1
from sales_main where transaction_date >= add_months(current_date(),-6)
group by sku,
'Sales_shift'
add_months(date_trunc('month',transaction_date),1),
Flag_field1),
table2 as (select sku,
date_type,
event_date,
Sales_total,
Refund_total,
Flag_field1,
case when Flag_field1 = 'type B' or (Flag_field1 = 'type A' and Sales_total > 20000) then 'Yes' else 'No' end as Flag_field2
from table1 )
Select sku,
date_type,
event_date,
Sales_total,
Refund_total,
Flag_field1
fromm table2 where Flag_field2 = 'Yes' )
union all
select sku,
'Refund' as date_type,
date_trunc('month',refund_date) as event_date,
sum(sales) as Sales_total,
sum(refund) as Refund_total,
'X' as Flag_field1
from sales_main where transaction_date >= add_months(current_date(),-6) and ColumnA = 'B'
group by sku,
'Refund'
date_trunc('month',refund_date),
'X'
union all
select sku,
'Sales_Reg' as date_type,
date_trunc('month',transaction_date) as event_date,
sum(sales) as Sales_total,
sum(refund) as Refund_total,
'Y' as Flag_field1
from sales_main where transaction_date >= add_months(current_date(),-6)
group by sku,
'Refund'
date_trunc('month',transaction_date),
'Y'