分组依据并显示最高计数(*)

d7v8vwbk  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(374)

我在做一个小项目,我想让每周票数最多的餐厅展示一次。

我的问题是:

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

结果如下:

我只想有一个与最高计数(*)显示每周。
谢谢你的帮助。

unftdfkk

unftdfkk1#

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

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

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

SELECT t.week, SUBSTRING_INDEX(GROUP_CONCAT(t.votedRestaurant ORDER BY t.total DESC),',',1) votedRestaurant, MAX(t.total)
FROM(
    SELECT votedRestaurant, WEEK, COUNT(*)  total
    FROM votes 
    GROUP BY votedRestaurant,WEEK 
    ORDER BY WEEK DESC
) t
GROUP BY t.week
ORDER BY t.week DESC

演示

qhhrdooz

qhhrdooz2#

例如,您可以尝试使用limit和按计数排序

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

此外,您还可以使用子查询,如文档所述。

相关问题