sql - 为每个组排序

时间:2016-07-24 07:44:24

标签: mysql sql

我有一个如下所示的查询:

SELECT
    USER .id,
    listing.country,
    count(listing.id) AS count
FROM    USER
INNER JOIN listing ON USER.id = listing.user_id
GROUP BY listing.country,   USER.id
ORDER BY count DESC;

我得到的结果如下:

enter image description here

但是我希望按国家/地区分组,以便用户可以按照其列表数量按国家/地区进行排名。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以拥有多个ORDER BY列:

SELECT `user`.`id`, 
       `listing`.`country`,
       count(`listing`.`id`) as `count` 
FROM `user` 
INNER JOIN `listing` ON (`user`.`id` = `listing`.`user_id`) 
GROUP BY `listing`.`country,` `user`.`id` 
ORDER BY `country`, `count` DESC;