with temp as (
select to_date('2018-3-31','yyyy-MM-dd') as 日期, '阿莫西林' as 商品,1 as 数量 from dual
union all
select to_date('2018-3-31','yyyy-MM-dd') as 日期, '阿莫西林' as 商品,2 as 数量 from dual
union all
select to_date('2019-2-28','yyyy-MM-dd') as 日期, '阿莫西林' as 商品,3 as 数量 from dual
union all
select to_date('2019-3-31','yyyy-MM-dd') as 日期, '阿莫西林' as 商品,4 as 数量 from dual
union all
select to_date('2019-3-31','yyyy-MM-dd') as 日期, '阿莫西林' as 商品,5 as 数量 from dual
union all
select to_date('2019-3-31','yyyy-MM-dd') as 日期, '阿莫西林' as 商品,6 as 数量 from dual
)
select a.日期,a.商品,a.数量 本期数量,b.数量 as 环比数量,c.数量 as 同比数量 from
(
select 日期,商品,sum(数量) 数量
from temp
group by 日期,商品
) a
left join (
select 日期,商品,sum(数量) 数量
from temp
group by 日期,商品
) b on to_char(a.日期,'yyyy-MM')=to_char(add_months(b.日期,1),'yyyy-MM') and to_char(a.日期,'dd')=to_char(b.日期,'dd') and a.商品=b.商品
left join (
select 日期,商品,sum(数量) 数量
from temp
group by 日期,商品
) c on a.日期=add_months(c.日期,12) and a.商品=c.商品
where a.日期=to_date('2019-03-31','yyyy-MM-dd')
![1571046334109853.png image.png](/upload/wenda/20191014/1571046334109853.png)