Mysql查询 - GROUP BY并显示最高COUNT(*)

时间:2018-06-14 08:59:13

标签: mysql

我正在做一个小项目,我试图让每周投票次数最多的餐厅显示一次。

Screen of database

这是我的疑问:

SELECT votedRestaurant,
       week,
       COUNT(*)
FROM mylunch.votes
GROUP BY votedRestaurant,
         week
ORDER BY week DESC;

这让我得到以下结果:

Screen of returned

我只想拥有每周显示最高COUNT(*)的那个。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用LIMIT并按计数排序,例如

      SELECT votedRestaurant,
           week,
           COUNT(*) AS tcount
    FROM mylunch.votes
    GROUP BY votedRestaurant,
             week
    ORDER BY tcount DESC
    LIMIT 1;

此外,您可以使用子查询,所以documentation

答案 1 :(得分:0)

使用Mysql 8可以使用窗口函数

fgets()

Demo

另一种方法是使用字符串函数

WITH
  cte AS  (SELECT votedRestaurant, WEEK, COUNT(*) total
            FROM votes 
            GROUP BY votedRestaurant,WEEK 
            ORDER BY WEEK DESC, votedRestaurant)
SELECT *
FROM (
SELECT *,
    row_number() over (PARTITION BY WEEK ORDER BY total DESC) AS rn
FROM 
    cte
 ) t
WHERE rn = 1

Demo