我的sql get id有最大的喜欢按列分组并按sum排序(喜欢)

时间:2018-04-20 11:39:54

标签: mysql sql

我需要从视图中检索数据。视图将包含详细信息,例如country,location_id,content_id,content_url,content_likes和....我需要检索location_id,其中max(content_likes)按国家/地区顺序按sum(content_likes)desc分组。

现在我正在根据国家/地区获取正确的数据,但我想知道哪个是默认顺序。但不是默认的有序ID,我需要获得最大喜欢的Id。

我当前的查询是

select * from <view_name> group by country order by sum(content_likes) desc;

观看数据:

enter image description here

结果:

enter image description here

3 个答案:

答案 0 :(得分:1)

你似乎想要这样的东西:

select country_id, location_id, sum(content_likes)
from view_name vn
group by country_id, location_id
having location_id = (select vn2.location_id
                      from view_name vn
                      where vn2.country_id = vn.country_id
                      group by location_id
                      order by sum(content_likes) desc
                      limit 1
                     );

答案 1 :(得分:0)

你可以尝试这个(抱歉任何语法错误):

    select cc.*
      from     
        (select aa.location_id, aa.country /*[, add fields if you need them...]*/,
               rank() over (partition by aa.country_id order by aa.content_likes) ranking_field
          from <view_name> aa
          join (select country, sum(content_likes) sum_content_likes
                  from <view_name>
                 group by country) bb
            on aa.country=bb.country) cc
    where ranking_field=1
order by cc.sum_content_likes desc

这将仅返回按每个国家/地区的总喜欢次数排序的每个国家/地区的最喜欢的位置

编辑:

使用你的新例子,也许你可以做到这一点:

SELECT *
  FROM <<view>> aa
  JOIN(SELECT country, MAX(content_likes) max_likes
         FROM <<view>>
        GROUP BY country) bb
    ON aa.country=bb.country
   AND aa.content_likes=bb.max_likes

这是两遍查询但是给出你的示例结果。如果多个位置具有相同的喜欢数量,那么它可以为国家/地区返回多行。这些是该国家/地区的最大喜欢。

希望这对你有所帮助。

答案 2 :(得分:0)

我的问题已在下面的sql中解决

select t.location_id,t.content_likes from 
(select country,max(content_likes) as mcl,sum(content_likes) as scl from test_eresh
group by country) x,
test_eresh t
where t.country = x.country
and t.content_likes = x.mcl
order by x.scl desc
相关问题