如何解决编写一个 SQL 查询,按渠道产生月收入和上个月的收入
Month_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,b.channel
order by a.year_month desc
,
试试这个代码。
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,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
输出:
,试试这个:
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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。