MySQL表参数方差

时间:2016-02-12 18:43:01

标签: mysql

我有一张这样的表:

=================================
| month | bread | milk | butter |
=================================
| Jan16 | 2.00  | 1.30 | 1.50   |
| Feb16 | 2.05  | 1.29 | 1.52   |
| March | 2.03  | 1.31 | 1.51   |
=================================

我想知道与第一个月相比价格的变化情况如何。 我希望得到类似的东西:

=================================
| month | bread | milk | butter |
=================================
| Jan16 | 1.00  | 1.00 | 1.0000 |
| Feb16 | 1.025 | 0.99 | 1.0133 |
| March | 1.015 | 1.01 | 1.0067 |
=================================

如何查询类似的内容:

SELECT bread[i]/bread[0] AS vBread, milk[i]/bread[0] as vMilk, butter[i]/butter[0] as vButter FROM table

2 个答案:

答案 0 :(得分:0)

1月份加入:

select a.month, a.bread/b.bread vBread, a.milk/b.milk vMilk, a.butter/b.butter vButter
from mytable a
join mytable b on b.month = 'Jan16';

答案 1 :(得分:0)

您可以分两步完成。首先将第一个月的值读入变量,第二个查询生成输出。

SELECT 
  bread,milk,butter 
  INTO @bread,@milk,@butter
FROM mytable
ORDER BY MONTH ASC
LIMIT 1;

SELECT 
  bread/@bread AS vBread,
  milk/@milk AS vMilk,
  butter/@butter AS vButter
FROM mytable;

或将其合并为一个:

SELECT 
  bread/@bread AS vBread,
  milk/@milk AS vMilk,
  butter/@butter AS vButter
FROM mytable,(
  SELECT 
  bread,milk,butter 
  INTO @bread,@milk,@butter
  FROM mytable
  ORDER BY MONTH ASC
  LIMIT 1 ) AS tmp;