Leetcode 1384. 按年度列出销售总额

1384.png

https://leetcode-cn.com/problems/total-sales-amount-by-year/

select a.product_id,b.product_name,a.report_year,a.y1 total_amount
from(
select product_id
,"2018" report_year
,average_daily_sales*(case when year(period_start)=2018 then 
   case when year(period_end)=2018 then datediff(period_end,period_start)+1 
        when year(period_end)>2018 then datediff('2018-12-31',period_start)+1 
    end
else 0 end) y1
from Sales
    union all 
select product_id
,"2019" report_year
,average_daily_sales*(case when year(period_start)=2018 then 
        case when year(period_end)=2019 then datediff(period_end,'2019-01-01')+1 
             when year(period_end)>2019 then 365 end
      when year(period_start)=2019 then 
        case when year(period_end)=2019 then datediff(period_end,period_start)+1 
             when year(period_end)>2019 then datediff('2019-12-31',period_start)+1 end
      else 0 end) y1
from Sales
    union all
select product_id
,"2020" report_year
,average_daily_sales*(case when year(period_start)<2020 then 
        case when year(period_end)=2020 then datediff(period_end,'2020-01-01')+1 end 
      when year(period_start)=2020 then 
        case when year(period_end)=2020 then datediff(period_end,period_start)+1 end
      else 0 end) y1
from Sales
)a left join Product b on a.product_id=b.product_id
where a.y1>0 
order by a.product_id,report_year
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容