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

1.3k Views Asked by At

Hey everyone I have two tables with output like this:

Month_Table

enter image description here

Transaction_Table enter image description here

I need to calculate the monthly revenue by channel and the previous month's revenue: I did this query but it is not completed

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

The result should be displaying monthly revenue and the month's revenue of previous month.

How can I do that?

3

There are 3 best solutions below

2
On BEST ANSWER

try this code .

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

output:

enter image description here

OR use this query

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

output:

enter image description here

3
On

You could try uing a a join between you tables

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
2
On

Try this:

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;