我对MYSQL全新,所以对这个问题表示道歉,但我不知道从哪里开始。
我有一个类似于下面的mysql表;
TABLE_1
Record_ID Price Price_Difference New_Value
1 100 null
2 101 1
3 115 14
4 135 20
5 95 -40
6 80 -15
我想要做的是添加和输入null的记录1,因为没有价格差异。
对于记录2,我希望'New_Value'为14的价格差值除以前一记录1中的价格值。
e.g。 14 / @ VAR_1
哪里
@var_1 = (case
when price_1 < 50 then 0.5
when price_1 between 50.001 and 100 then 1
when price_1 between 100.001 and 150 then 1.25
when price_1 between 150.001 and 150 then 1.4
....etc.
end case
我认为这可以在MYSQL中完成,并且我可以如何理解它?
答案 0 :(得分:3)
这可以通过连接同一个表的两个别名来完成,其中一个指向当前Record_ID
,另一个指向前一个Record_ID
,在连接条件中加1。 / p>
这只有在Record_ID
的行保证顺序且没有间隙的情况下才有效。
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
如果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