请教一下各位,我在excel表中单元格的公式是根据上一行的数据实现的。只有第一行是原有数据,请问这在sql2012中如何实现
3 个解决方案
#1
lag 和 lead 这两个函数,可以满足你的需求。
#2
2012可以用lag和lead,之前的可以这样实现
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([value] int)
Insert #T
select 10 union all
select 21 union all
select 35
Go
--测试数据结束
;WITH cte AS (
SELECT *,ROW_NUMBER()OVER(ORDER BY value) AS rn FROM #T
)
SELECT CASE WHEN b.value IS NOT NULL THEN b.value
ELSE a.value
END
FROM cte a
LEFT JOIN cte b ON a.rn - 1 = b.rn
#3
硬脚本仅供参考:
if object_id('test')is not null
drop table test
go
create table test(id int,num numeric(18,2),perc numeric(3,2))
go
insert into test
select 1,100000,0.5
go
;with cte as
(
select t.id,t.num,t.perc,1 as [level] from test t where num = 100000
union all
select c.id+1,convert(numeric(18,2),c.num * c.perc) as num,c.perc,c.level+1 from cte c where [level] between 1 and 10
)
insert into test
select id,num,perc from cte where level <>1
go
select * from test
#1
lag 和 lead 这两个函数,可以满足你的需求。
#2
2012可以用lag和lead,之前的可以这样实现
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([value] int)
Insert #T
select 10 union all
select 21 union all
select 35
Go
--测试数据结束
;WITH cte AS (
SELECT *,ROW_NUMBER()OVER(ORDER BY value) AS rn FROM #T
)
SELECT CASE WHEN b.value IS NOT NULL THEN b.value
ELSE a.value
END
FROM cte a
LEFT JOIN cte b ON a.rn - 1 = b.rn
#3
硬脚本仅供参考:
if object_id('test')is not null
drop table test
go
create table test(id int,num numeric(18,2),perc numeric(3,2))
go
insert into test
select 1,100000,0.5
go
;with cte as
(
select t.id,t.num,t.perc,1 as [level] from test t where num = 100000
union all
select c.id+1,convert(numeric(18,2),c.num * c.perc) as num,c.perc,c.level+1 from cte c where [level] between 1 and 10
)
insert into test
select id,num,perc from cte where level <>1
go
select * from test