這將會給你的整體。請確保您希望以訂單 - 我已經按id訂購
SET @runtot:=0;
SET @prevval:=0;
select max(rt) as total FROM (
SELECT
q.val,
q.num,
(@runtot := @runtot + (q.num- @prevval) * q.val) AS rt,
(@prevval := q.num) AS pv
FROM thetable q
ORDER by ID) tot
如果你想看到計算的細節,離開了外選擇像這樣:
SET @runtot:=0;
SET @prevval:=0;
SELECT
q.val,
q.num,
(@runtot := @runtot + (q.num- @prevval) * q.val) AS rt,
(@prevval := q.num) AS pv
FROM thetable q
ORDER by ID
如果有可能對你的列值有負數,使用max(rt)將不適用於總數。然後,您應該使用:
SET @runtot:=0;
SET @prevval:=0;
select @runtot as total FROM (
SELECT
q.val,
q.num,
(@runtot := @runtot + (q.num- @prevval) * q.val) AS rt,
(@prevval := q.num) AS pv
FROM thetable q
ORDER by ID) tot LIMIT 1
我在想: 選擇 總和((a.num - ifnull(b.num,0))* a.val)作爲結果 from tt a left join tt b on b.id =(a.id - 1); 但是,這個假設ID總是增加一。我喜歡連接中的變量技巧。 –
謝謝,它正在工作,但我意識到我已經從問題中排除了我的問題的關鍵部分,請問您可以在這裏查看我修改的問題嗎? :[鏈接](http://stackoverflow.com/questions/22726266/mysql-recursive-substracting-and-multiplying-grouped-values) – Sevron