0

大家好,我有两张表,输出如下:

Month_Table

在此处输入图像描述

事务表 在此处输入图像描述

我需要按渠道计算月收入和上个月的收入:我做了这个查询但没有完成

Select date_created, channel, sum(revenue) as monthly_revenue 
from transaction_table  
GROUP BY  date_created,channel

结果应显示每月收入和上个月的当月收入。

我怎样才能做到这一点?

4

3 回答 3

1

您可以尝试在您的表之间使用 aa join

Select a.month_index, a.year_month, b.channel, sum(b.revenue) as monthly_revenue 
from Month_Table a 
from transaction_table  b ON b.date_created between a.month_start_date and a.month_and_date
    amd month(b.date_created) = betwwen month(curdate()) -1 and month(curdate())
GROUP BY  a.month_index, a.year_month, b.channel
order by a.year_month desc
于 2021-02-22T09:06:54.203 回答
1

试试这个代码。

with resultTable as(
select RT.channel,RT.sumRevenue,LT.[month-start_date],LT.month_end_date,LT.year_month
from (select t.channel,sum(revenue) as sumRevenue,M.month_index from Month_Table M,Transaction_Table T
where t.date_created BETWEEN m.[month-start_date] AND m.month_end_date
group by m.month_index,t.channel) RT Join Month_Table LT on RT.month_index = LT.month_index
)
select * from resultTable

输出:

在此处输入图像描述

或使用此查询

with resultTable as(
select RT.channel,RT.sumRevenue,LT.[month-start_date],LT.month_end_date,LT.year_month
from (select t.channel,sum(revenue) as sumRevenue,M.month_index from Month_Table M,Transaction_Table T
where t.date_created BETWEEN m.[month-start_date] AND m.month_end_date
group by m.month_index,t.channel) RT Join Month_Table LT on RT.month_index = LT.month_index
)
select *,LAG(sumRevenue,1) OVER (PARTITION BY channel ORDER BY channel) previous_month_sales from resultTable

输出:

在此处输入图像描述

于 2021-02-22T11:52:36.213 回答
0

尝试这个:

Select t1.date_created, t1.channel, sum(t1.revenue) as monthly_revenue ,sum(t2.revenue) prev_month_revenue
from transaction_table t1 left join transaction_table t2  on t1.channel = t2.channel and to_char(t1.date_created,'MM') = to_char(add_months(t2.date_created,-1),'MM')
GROUP BY  t1.date_created,t1.channel;
于 2021-02-22T10:15:35.603 回答