在SQL SELECT中查找MAX的COUNT

时间:2017-07-14 09:28:24

标签: mysql count sum

我有时间,距离,步速等运行的SQL表信息...我希望按用户的月份获得最佳最大运行距离的信息。我需要每个月计算一次跑步距离并找到最好的一个(MAX)。

我的表格如下:

+----+--------+--------+----------+
| ID | USERID | MONTH  | DISTANCE |
+----+--------+--------+----------+
| 1  |    1   | 201707 |   6.69   |
+----+--------+--------+----------+
| 2  |    2   | 201707 |   6.03   |
+----+--------+--------+----------+
| 3  |    2   | 201707 |   6.02   |
+----+--------+--------+----------+
| 4  |    1   | 201706 |   7.25   |
+----+--------+--------+----------+
| 5  |    1   | 201706 |   7.13   |
+----+--------+--------+----------+
| 6  |    2   | 201705 |   7.03   |
+----+--------+--------+----------+
| 7  |    3   | 201705 |   6.31   |
+----+--------+--------+----------+
| 8  |    1   | 201705 |   5.28   |
+----+--------+--------+----------+
| 9  |    1   | 201704 |   4.44   |
+----+--------+--------+----------+
| 10 |    2   | 201704 |   5.94   |
+----+--------+--------+----------+

我试试这个,但我没有输出:

$select3run = mysqli_query($conn, "SELECT month, MAX(mycount) FROM (SELECT month, SUM(distance) AS mycount FROM runbeh GROUP BY month, distance) a GROUP BY month");
while($data=mysqli_fetch_array($select3run)) {
$max=$data['mycount'];
}

echo $max;

不知道如何找到我正在寻找的价值。有人可以帮帮我吗?

4 个答案:

答案 0 :(得分:0)

您应该为列名使用适当的别名,例如:my_max

    $select3run = mysqli_query($conn, "
        SELECT month, MAX(mycount)  as my_max
        FROM (SELECT month, SUM(distance) AS mycount 
        FROM runbeh GROUP BY month, distance) a 
        GROUP BY month");
    while($data=mysqli_fetch_array($select3run)) {
      $max=$data['my_max'];
    }

    echo $max;

答案 1 :(得分:0)

示例:

http://sqlfiddle.com/#!9/29009f/8

SQL:

SELECT r.userid, r.month, max(r.sumdistance) 
FROM
(
  SELECT userid, month, sum(distance) as sumdistance 
  FROM runners 
  GROUP BY month, userid
) as r 
GROUP BY r.userid

答案 2 :(得分:0)

解决!

非常感谢Raimondas Kazlauskas和scaisEdge,他们向我展示了方向并帮助了我。

显示用户每月运行的最远距离的工作代码:

$select3run = mysqli_query($conn, "SELECT month, MAX(mycount)  as my_max 
FROM
(SELECT month, SUM(distance) AS mycount FROM runners GROUP BY month) a GROUP 
BY mycount DESC LIMIT 1");
while($data=mysqli_fetch_array($select3run)) {
$max=$data['my_max'];
echo $max; }

其中$ max是用户运行一个月的最大距离和。

答案 3 :(得分:-1)

你应该尝试这个: -

每个用户每个月最好的运行: -

选择max(距离)AS MaxDistance,来自runbeh group by userid的用户ID,userid

注意: - 永远不要在Group BY子句中放置任何聚合函数