我想在SQL中进行递归计算,但是,显然我不能滞后于同一查询创建的列。使用示例 Id Column1 Column2
1 5 10
2 2 x
3 3 y
:
lag()
我想将x替换为0.5 * 2 + 10,将y替换为0.5 * 3 + x。
select
Id
, Column1
, case when Id = 1 then 10
when Id > 1 then 0.5 * Column1 + lag(Column2, 1) over (order by Id)
else null end as Column2
from table
的查询如下所示:
// Non-Angular Example
@Component({})
class FooComponent {
public appState: AppState;
constructor(DI: DependencyInjector) {
this.appState = DI.get('AppState');
}
ngOnInit() {}
}
在SQL中有一种简单的方法吗?
编辑:此表将比示例中的表长得多,因此解决方案应该考虑这一点。
答案 0 :(得分:0)
以下案例陈述
when Id > 1 then 0.5 * Column1 + lag(Column2, 1) over (order by Id)
返回两个值ID = 2和Id = 3,因此返回不正确的值。
我知道会有更好的评价。
检查出来:
create table recur
(
Id int,
Column1 int,
Column2 varchar(100)
);
insert into recur values ( 1,5,10);
insert into recur values ( 2,2,'x');
insert into recur values (3,3,'y');
select * from
(select
a.Id,a.Column1,
case when a.Id = 1 then 10
when a.Id =2 then (0.5 * a.Column1 + lag(a.Column2 , 1) over (order by a.Id) )
else null end as Column2
from recur a
union
select id,column1,
case when Id =3 then (0.5 * Column1 + lag(Column2 , 1) over (order by Id) )end as Column2
from
(
select
a.Id,a.Column1,
case when a.Id = 1 then 10
when a.Id =2 then (0.5 * a.Column1 + lag(a.Column2 , 1) over (order by a.Id) )
else null end as Column2
from recur a)b
)c
where column2 is not null
此致 Saravanan