使用group by仅显示最佳总结结果

时间:2018-05-10 01:07:00

标签: mysql sql

我的表记录了同一组用户的三个不同分数(站点,公园,分区)。 用户的总分是“所有站点得分的总和”+“所有公园得分的总和”+“所有得分的总和”。

代码如下,我正在使用MySQL:

select  sum(points)as points, user_name 
from 
(SELECT sum(site_point) as points, user_name from visits v join users u on 
u.user_id = v.user_id group by user_name
union 
select sum(park_point) as points , user_name  from visits v join users u on                 
u.user_id = v.user_id group by user_name
union
select sum(division_point) as points , user_name  from visits v join users u 
on u.user_id = v.user_id  group by user_name
) V group by user_name  order by sum(points) DESC ;

我想只显示得分在前5名的用户及其分数。 十个用户可能具有相同的最高分。我需要显示所有这些内容。 我感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

我认为这就是你想要的:

select user_name,
       sum(site_point + park_point + division_point) as points
from visits v join
     users u
     on u.user_id = v.user_id
group by user_name
order by points desc
limit 5;

单个聚合简化了计算。

您可能没有意识到,但union在某些情况下会返回不正确的结果。 Union删除重复项,因此如果用户具有相同的部分分数,则这两行将成为一个。

编辑:

获得前5个分数有点棘手,但可能:

select user_name,
       sum(site_point + park_point + division_point) as points
from visits v join
     users u
     on u.user_id = v.user_id
group by user_name
having points >= (select distinct points
                  from (select sum(site_point + park_point + division_point)
                        from visits v join
                             users u
                             on u.user_id = v.user_id
                        group by user_name
                       ) vu
                  order by points desc
                  limit 1 offset 4
                 )
order by points desc
limit 5;

假设user_name对于给定的ID是唯一的,您可以简化这一点:

having points >= (select distinct points
                  from (select sum(site_point + park_point + division_point) as points
                        from visits v 
                        group by user_id
                       ) vu
                  order by points desc
                  limit 1 offset 4
                 )

并且,如果您希望任何匹配前5位用户的人 - 但如果存在关联则返回超过5行 - 则将子查询中的select distinct更改为select

答案 1 :(得分:0)

使用LIMIT命令。更多信息here

所以要将它添加到你的SQL上会导致:

select  sum(points)as points, user_name 
from 
(SELECT sum(site_point) as points, user_name from visits v join users u on 
u.user_id = v.user_id group by user_name
union 
select sum(park_point) as points , user_name  from visits v join users u on                 
u.user_id = v.user_id group by user_name
union
select sum(division_point) as points , user_name  from visits v join users u 
on u.user_id = v.user_id  group by user_name
) V group by user_name  order by sum(points) DESC LIMIT 5