有一种很好的方法可以让一个查询将值乘以相同计算值(本身)与上一行按某一列分组。下面我有一个表格,其中有两个按日期排序的帐户。 (轻微扭曲,如果没有前一行使用1)。值是计算值,并分别在每个帐户上计算。
注意:我已在每个查询结果的括号中显示了Value的计算。
初始表
Account Date ChangePct
547 10/24/17 .997715
547 10/26/17 .973493
547 10/27/17 1.001300
547 10/30/17 .999541
600 10/26/17 1.004650
600 10/27/17 1.000996
600 10/30/17 .995000
600 10/31/17 .996176
查询结果
Account Date ChangePct Value
547 10/24/17 .997715 .997715 (.997715 * 1)
547 10/26/17 .973493 .971268 (.973493 * .997715)
547 10/27/17 1.001300 .972531 (1.001300 * .971268)
547 10/30/17 .999541 .972084 (.999541 * .972531)
600 10/26/17 1.004650 1.004650 (1.004650 * 1)
600 10/27/17 1.000996 1.005651 (1.000996 * 1.004650)
600 10/30/17 .995000 1.000622 (.995000 * 1.005651)
600 10/31/17 .996176 .996796 (.996176 * 1.000622)
答案 0 :(得分:0)
<强> SCHEMA:强>
CREATE TABLE test (
account INT,
date1 date,
change_pct decimal(7,6)
);
INSERT INTO test (account,date1,change_pct) VALUES (547, STR_TO_DATE("10/24/17", "%m/%d/%Y"), .997715);
INSERT INTO test (account,date1,change_pct) VALUES (547, STR_TO_DATE("10/26/17", "%m/%d/%Y"), .973493);
INSERT INTO test (account,date1,change_pct) VALUES (547, STR_TO_DATE("10/27/17", "%m/%d/%Y"), 1.001300);
INSERT INTO test (account,date1,change_pct) VALUES (547, STR_TO_DATE("10/30/17", "%m/%d/%Y"), .999541);
INSERT INTO test (account,date1,change_pct) VALUES (600, STR_TO_DATE("10/26/17", "%m/%d/%Y"), 1.004650);
INSERT INTO test (account,date1,change_pct) VALUES (600, STR_TO_DATE("10/27/17", "%m/%d/%Y"), 1.000996 );
INSERT INTO test (account,date1,change_pct) VALUES (600, STR_TO_DATE("10/30/17", "%m/%d/%Y"), .995000);
INSERT INTO test (account,date1,change_pct) VALUES (600, STR_TO_DATE("10/31/17", "%m/%d/%Y"), .996176);
<强> QUERY:强>
select
account,
date1,
change_pct,
@prev_acct as ss,
case
when @prev_acct = 1 then
@prev_acct:=account
when @prev_acct = account then
@prev_acct:=account
when @prev_acct != account then
@prev_acct:=account and @multi:=1
else
@prev_acct:=account
end as s,
(@multi := change_pct * @multi) as value
from
test,
(select @multi:=1, @prev_acct:= 1) t1
order by
account,
date1;