我有下表:
name date price
productA Jan2019 3000
productA Feb2019 3500
productA Mar2019 3200
productB Jan2019 2500
productB Feb2019 2700
productB Mar2019 2800
我想计算每种产品的Mar2019和Feb2019变化百分比。例如,对于产品A,该百分比为(3200-3500)/3500=-8.6%
所需的结果是
name date %change
productA Mar2019 -8.6
productB Mar2019 3.7
如何编写sql命令? 谢谢
答案 0 :(得分:2)
您可以使用条件聚合。像这样:
select name,
(1 -
max(case when date = 'Mar2019' then price end) /
max(case when date = 'Feb2019' then price end)
)
from t
group by name
答案 1 :(得分:0)
为了使过程更加简洁,我建议您将日期存储为日期并将其设置为每月的第一天。这样,将更容易加入。您将加入该产品,并且日期少于上个月的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