根据一些标准选择每个重复元组的顶行(MYSQL)

时间:2015-04-26 12:35:13

标签: mysql group-by

我有一个这样的示例表:

  

月城市人   8 LHR ABC
  10北京BCS
  11 NY JJJ
  11威尼斯hghg
  11威尼斯KKK
  12 NY aa
  12 ORL abc
  12 ORL bbc

所以我想要达到的目标是在特定月份看到参观人数最多的城市

就像输出应该是:

12 ORL  
11 VENINCE  
10 BEIJING  
8 LHR 

我尝试将其分组为

SELECT month, city , count(*) AS 'no of people visiting'     
FROM table
GROUP BY month, city   

此表确实告诉我哪个城市和月份位置有多少人 访问,但我无法提取最顶部的月份和城市组合
就某个月而言。

更新了查询(有错误)

SELECT *  
FROM   
( SELECT monthname(reservation.PickupDate), location.LocationName, COUNT(*) AS count
FROM reservation  NATURAL JOIN location
WHERE reservation.pickupdate >= DATE_ADD(NOW(), INTERVAL - 3 MONTH)
GROUP BY month(reservation.PickupDate), location.LocationName) AS t1
WHERE NOT EXISTS (SELECT 1
FROM reservation R1 NATURAL JOIN location L1
WHERE  monthname(R1.PickupDate) = monthname(t1.PickupDate)
GROUP BY month(R1.PickupDate), L1.LocationName) 

1 个答案:

答案 0 :(得分:1)

从您的查询开始,您只需要删除那个月内拥有更多访问者的其他城市的行:

SELECT * 
FROM
  (SELECT `month`, city, count(*) AS cnt 
  FROM `table` 
  GROUP BY `month`, city) t1
WHERE NOT EXISTS(SELECT 1 
  FROM `table` t2 
  WHERE t2.`month` = t1.`month`
  GROUP BY `month`, city 
  HAVING count(*) > t1.cnt)