select d.*,case when (d.同期增长值*1.00/d.'2020当月销量'*1.00) is null then 0 else (d.同期增长值*1.00/d.'2020当月销量'*1.00) end 同比 from
(select c.yearmonth '2020年月',c.saleamount '2020当月销量',b.yearmonth '2021年月',b.saleamount '2021当月销量',
b.saleamount - c.saleamount 同期增长值 from
(select * from (
select a.*,substr(a.yearmonth,0,5) year,substr(a.yearmonth,6,2) month
from sql2003 a
join
(select *,substr(yearmonth,0,5) year,substr(yearmonth,6,2) month from sql2003) b on a.yearmonth = b.yearmonth)
where year = '2020') c
join
(select * from (
select a.*,substr(a.yearmonth,0,5) year,substr(a.yearmonth,6,2) month
from sql2003 a
join
(select *,substr(yearmonth,0,5) year,substr(yearmonth,6,2) month from sql2003) b on a.yearmonth = b.yearmonth)
where year = '2021') b where b.month = c.month) d order by d.'2020年月'
=======================
SELECT
a.yearmonth 年月,
a.saleamount 当月销量,
case when (( a.saleamount - a.前一月销量 ) * 1.00 / a.前一月销量 * 1.00) is null then 0 else (( a.saleamount - a.前一月销量 ) * 1.00 / a.前一月销量 * 1.00) end 环比
FROM
( SELECT *, lag( coalesce( saleamount, 0 ), 1 ) OVER ( ORDER BY yearmonth ) 前一月销量 FROM sql2003 ) a
ORDER BY
yearmonth