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
2条答案
按热度按时间unftdfkk1#
使用mysql 8可以使用窗口函数
演示
另一种方法是使用字符串函数
演示
qhhrdooz2#
例如,您可以尝试使用limit和按计数排序
此外,您还可以使用子查询,如文档所述。