这可以通过连接同一个表的两个别名来完成,其中一个指向当前Record_ID
,另一个指向前一个Record_ID
,方法是在连接条件中将其加 1。
这只有在Record_ID
保证 for 的行是连续的且没有中间间隙的情况下才有效。
SELECT
pcur.Price,
pcur.Price_Difference,
CASE
WHEN plast.Price < 50 THEN (pcur.Price_Difference / 0.05)
WHEN plast.Price BETWEEN 50.001 AND 100 THEN (pcur.Price_Difference / 1)
WHEN plast.Price BETWEEN 100.001 AND 150 THEN (pcur.Price_Difference / 1.25)
WHEN plast.Price BETWEEN 150.001 AND 200 THEN (pcur.Price_Difference / 1.4)
ELSE 999 # don't forget your else case
END AS var_1
FROM
/* First aliased table is the current record */
prices pcur
/* Second aliased table is the previous one, whose id is one behind */
LEFT JOIN prices plast ON (pcur.Record_ID = plast.Record_ID + 1);
这是一个演示:http ://sqlfiddle.com/#!2/552ee/7
如果序列中存在潜在间隙,则使用子选择通过and从前一行Record_ID
检索较慢的方法将起作用。这在大型数据集上不会有超强的性能。Price
ORDER BY
LIMIT 1
SELECT
rid,
Price,
Price_Difference,
CASE
WHEN var_1 < 50 THEN (Price_Difference / 0.05)
WHEN var_1 BETWEEN 50.001 AND 100 THEN (Price_Difference / 1)
WHEN var_1 BETWEEN 100.001 AND 150 THEN (Price_Difference / 1.25)
WHEN var_1 BETWEEN 150.001 AND 200 THEN (Price_Difference / 1.4)
ELSE 999 # don't forget your else case
END AS var_1
FROM (
SELECT
Record_ID rid,
Price,
Price_Difference,
/* Subselect returns only one Price from the previous Record_ID which may not be in sequence */
(SELECT Price FROM prices WHERE Record_ID < rid ORDER BY Record_ID DESC LIMIT 1) AS var_1
FROM prices
) pcalc
这是一个演示:http ://sqlfiddle.com/#!2/552ee/5