27,579
社区成员
发帖
与我相关
我的任务
分享
--测试数据
if not object_id(N'Tempdb..#table1') is null
drop table #table1
Go
Create table #table1([id] int,[num] FLOAT,[date] Date)
Insert #table1
select 1,50,'2018-3-31' union all
select 2,40,'2017-3-31' union all
select 3,30,'2016-3-31'
Go
--测试数据结束
select *,增长率=([num]-lead([num])over(order by [date] desc))/lead([num])over(order by [date] desc)*100
from #table1
id num date 增长率
----------- ---------------------- ---------- ----------------------
1 50 2018-03-31 25
2 40 2017-03-31 33.3333333333333
3 30 2016-03-31 NULL
--测试数据
if not object_id(N'Tempdb..#table1') is null
drop table #table1
Go
Create table #table1([id] int,[num] FLOAT,[date] Date)
Insert #table1
select 1,50,'2018-3-31' union all
select 2,40,'2017-3-31' union all
select 3,30,'2016-3-31'
Go
--测试数据结束
SELECT
a.date,
CASE
WHEN b.num IS NOT NULL
THEN (a.num - b.num) / b.num
ELSE
0
END AS 增长率
FROM
#table1 a
LEFT JOIN
#table1 b
ON a.id = b.id - 1;
;with cte(Id,num,date) as(
select 1, 50.00,'2018-03-31'
union all select 2,40.00,'2017-03-31'
union all select 3,30.00,'2016-03-31'
)
select a.num as ANum,b.num as BNum,(a.num-b.num)/b.num as Rate from cte a, cte b
where a.date='2018-03-31' and b.date='2017-03-31'