mysql 力扣,1384. 按年度列出销售总额

  1. 按年度列出销售总额
    https://leetcode-cn.com/problems/total-sales-amount-by-year/
    在这里插入图片描述
    在这里插入图片描述
with sc as (
    select product_id,'2018' report_year ,sum(datediff(
    if(datediff('2018-12-31',period_end)>0,period_end,'2018-12-31') ,
    if (datediff('2018-01-01',period_start)>0,'2018-01-01',period_start))+1)*average_daily_sales money
    from sales
    where year(period_start)<=2018 and year(period_end)>=2018
    group by product_id
    union
    select product_id,'2019' report_year ,sum(datediff(
    if(datediff('2019-12-31',period_end)>0,period_end,'2019-12-31') ,
    if (datediff('2019-01-01',period_start)>0,'2019-01-01',period_start))+1)*average_daily_sales money
    from sales
    where year(period_start)<=2019 and year(period_end)>=2019
    group by product_id
    union
    select product_id,'2020' report_year ,sum(datediff(
    if(datediff('2020-12-31',period_end)>0,period_end,'2020-12-31') ,
    if (datediff('2020-01-01',period_start)>0,'2020-01-01',period_start))+1)*average_daily_sales money
    from sales
    where year(period_start)<=2020 and year(period_end)>=2020
    group by product_id)
    
select sc.product_id,p.product_name,sc.report_year,sc.money total_amount
from sc join product p on sc.product_id = p.product_id
order by  product_id,report_year

##额,看着挺长的,其实都是重复的,核心的思想就是把每一年的销售总额求出来,
#一年一年的求,求出一个其它的就改下日期的范围照抄就好了。这里以2019年为列子。
###1,先看过滤条件,year(period_start)<=2019 and year(period_end)>=2019 
#将涉及到2019年的每一条销售信息过滤了出来。
###2,两个if的意思就是说,如果开始日期比19年的第一天还要小,开始日期就用2019-01-01
####如果结束日期比19年的最后一天还要大没结束日期就用19年的最后一天。
##然后求出开始与结束的时间差,在乘上每日的销售额。按照id分组,就是19年每种类别的销售额了。
##(ps:我这里好像日期做差比答案少一一天,是包含不包含的问题,我就在后面加了一。)
select product_id,'2019' report_year ,sum(datediff(
    if(datediff('2019-12-31',period_end)>0,period_end,'2019-12-31') ,
    if (datediff('2019-01-01',period_start)>0,'2019-01-01',period_start))+1)*average_daily_sales money
    from sales
    where year(period_start)<=2019 and year(period_end)>=2019
    group by product_id

这样最后将其它两年求出来,合并,然后和产品名字的表内联,就是最后的答案了。

猜你喜欢

转载自blog.csdn.net/qq_42232193/article/details/106676648