1

我对 MYSQL 完全陌生,因此为这个问题道歉,但我不知道从哪里开始。

我有一个如下所示的 mysql 表;

表格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 中价格的值。

例如 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 中完成,我想我该怎么做?

4

1 回答 1

4

这可以通过连接同一个表的两个别名来完成,其中一个指向当前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检索较慢的方法将起作用。这在大型数据集上不会有超强的性能。PriceORDER BYLIMIT 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

于 2013-08-13T00:09:35.957 回答