請參考上圖。
我有表1,我想用SQL產生表2。
元年必須被設置爲值10以下將由乘法器乘10當年和往年於表1
對於示例中的值:
- 對於2002年(2002年乘數)* 1(2001年乘數)= 20。
- 2005年的數值爲10 * 5 * 3 * 1 * 2 * 1(前一年所有乘數)= 300 。
我會如何去做這件事?我會很感激任何幫助。
請參考上圖。
我有表1,我想用SQL產生表2。
元年必須被設置爲值10以下將由乘法器乘10當年和往年於表1
對於示例中的值:
我會如何去做這件事?我會很感激任何幫助。
我的一位同事很早就教會了我使用對數特性來解決這類問題的技巧。
基本上,你可以這樣做:
Exp(sum(ln(multiplier)))
的OP後,編輯讓我意識到這是不完整的
要你需要,你應將此上累積邏輯自聯接
select a.youryear, Exp(sum(ln(b.multiplier))) cumulative_mutiplier
from yourtable as a
join
yourtable as b on a.youryear>=b.youryear
group by a.youryear;
我準備了一個測試rextester
create table yourtable (
youryear integer,
multiplier integer
);
insert into yourtable(youryear,multiplier) values (2000,10);
insert into yourtable(youryear,multiplier) values (2001,1);
insert into yourtable(youryear,multiplier) values (2002,2);
insert into yourtable(youryear,multiplier) values (2003,1);
insert into yourtable(youryear,multiplier) values (2004,3);
insert into yourtable(youryear,multiplier) values (2005,5);
select a.youryear, Exp(sum(ln(b.multiplier))) cumulative_mutiplier
from yourtable as a
join
yourtable as b on a.youryear>=b.youryear
group by a.youryear;
結果是:
youryear cumulative_mutiplier
1 2000 10
2 2001 10
3 2002 20
4 2003 20
5 2004 60
6 2005 300
select year
,x
,@result := @result*coalesce(x,10) as result
from table1,(select @result:=1) i
order by year
;
# year, x, result
2000, , 10
2001, 1, 10
2002, 2, 20
2003, 1, 20
2004, 3, 60
2005, 5, 300
哪個關係數據庫管理系統/版本是你嗎? –
在哪個rdbms上? – Insac
有了SQL Server,你可以使用'over partition' – Hackerman