为了使这个过程更加干净,我建议将日期存储为日期,并将其设置为每月的第一天。这样就更容易连接了。你将加入产品和日期少于1个月的前一个月。如果没有上个月,我输入
NA
create table #test (
name varchar(16)
,[date] date
,price decimal(18,2)
)
insert into #test
values ('productA', '2019-01-01', 3000),
('productA', '2019-02-01', 3500),
('productA', '2019-03-01', 3200),
('productB', '2019-01-01', 2500),
('productB', '2019-02-01', 2700),
('productB', '2019-03-01', 2800)
select a.name name
,format(a.date,'yyyyMM') [date]
,case
when b.date is not null then cast(cast((a.price - b.price)/b.price * 100 as decimal(18,1)) as varchar(25)) + '%'
else 'NA'
end change
from #test a
left join #test b on b.name = a.name
and b.[date] = dateadd(month,-1,a.date)
drop table #test