如何将列的最大值存储为变量,然后将其用于MySQL中的计算?

时间:2016-05-22 03:55:08

标签: mysql max

这是我正在使用的代码。

  Select max(heart_rate) as Max_heart, Count(*) from exercise_logs 
  where heart_rate between (0.5*Max_heart) and (0.9*Max_heart);

我是SQL的新手,但我认为这对于像R这样的东西很容易。不管怎么说,因为我需要在SQL中完成这个,所以有关如何做到这一点的任何建议?

我的数据看起来像这样

  type            minutes calories heart_rate
  biking          30      100      110
  biking          10       30      105
  dancing         15      200      120
  dancing         15      165      120
  tree climbing   30       70       90
  tree climbing   25       72       80
  rowing          30       70       90
  hiking          60       80       85

2 个答案:

答案 0 :(得分:0)

您想使用User-Defined Variables。它应该像

  declare var1, var2 INT;

  Select var1 = max(heart_rate), var2 = Count(*) 
  from exercise_logs 
  where heart_rate between (0.5*Max_heart) and (0.9*Max_heart);

  select var1 + var2 as Data;

答案 1 :(得分:0)

试试这个

-- Finds maximum heart rate from all activities
SET @Max_heart := ( SELECT  max(heart_rate) FROM exercise_logs );

-- Selects activities that generate between 50% and 90% of the maximum heart rate
Select *
FROM exercise_logs
where heart_rate between (0.5* @Max_heart) and (0.9*@Max_heart);