MySQL Query分组和计数结果

时间:2016-03-23 11:28:44

标签: mysql

这是我当前的查询 - 它显示城市和距离值:

SELECT city, ( 6371 * acos( cos( radians(51.228482) ) * cos( radians( geo_breit
 ) ) * cos( radians( geo_lang ) - radians(6.772457) ) + sin( radians(51.228482) ) * sin( radians( geo_breit
 ) ) ) )
   AS distance
   FROM partner HAVING distance < 50 
   ORDER BY city

输出:

enter image description here

我完全迷失了对数据的分组,因此会返回以下内容

city                    total         max_distance
-------------------------------------------------------------
Bedburg                 2             29.445788818447983
Bergheim                2             32.83341311371813
Bergisch Gladbach       4             39.62206615477636
Bochum                  1             43.15766028349356
...

编辑:我添加了实际查询,问题是在使用HAVING关键字时,分组/最大不起作用..任何想法?

4 个答案:

答案 0 :(得分:1)

要么使用这样的嵌套查询:

SELECT cities.city,
       count(*) as total,
       max(cities.distance) as max_distance
FROM (SELECT city,
            ( 6371 * acos( cos( radians(51.228482) ) * cos( radians( geo_breit ) ) * cos( radians( geo_lang ) - radians(6.772457) ) + sin( radians(51.228482) ) * sin( radians( geo_breit) ) ) ) AS distance
       FROM partner HAVING distance < 50 
       ORDER BY city) as cities
  GROUP BY cities.city

您可以使用where子句而不是

来尝试
    SELECT city, count(*),
            max( 6371 * acos( cos( radians(51.228482) ) * cos( radians( geo_breit ) ) * cos( radians( geo_lang ) - radians(6.772457) ) + sin( radians(51.228482) ) * sin( radians( geo_breit) ) ) ) AS max_distance
       FROM partner 
       WHERE (6371 * acos( cos( radians(51.228482) ) * cos( radians( geo_breit ) ) * cos( radians( geo_lang ) - radians(6.772457) ) + sin( radians(51.228482) ) * sin( radians( geo_breit) ) ) < 50 
       ORDER BY city
       GROUP BY city

答案 1 :(得分:0)

SELECT city, COUNT(city) as total, MAX(distance) AS max_distance
FROM table
GROUP BY city

答案 2 :(得分:0)

您可以使用COUNT函数计算出现次数和MAX函数来查找 GROUP BY

的最大距离值

<强>查询

select city, count(city) as total, max(distance) as max_distance
from your_table_name
group by city;

答案 3 :(得分:0)

使用GROUP BY

SELECT city, COUNT(city) total, MAX(distance) max_distance
FROM table
GROUP BY city

GROUP BY语句与聚合函数结合使用,可以按一列或多列对结果集进行分组。