编写一个 SQL 查询,按渠道生成每月收入和上个月的收入

Compose a SQL query that produces monthly revenue by channel and the previous month's revenue

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

Month_Table

Transaction_Table

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

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

结果应该是显示月收入和上个月当月收入。

我该怎么做?

您可以尝试在表之间使用连接

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

试试这个:

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;

试试这个代码。

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

输出: