Mysql 我的sql get id,它具有按列分组并按总和排序的最大喜欢数(喜欢数)
我需要从视图中检索数据。视图将包含诸如国家、位置、内容、url、内容和。。。。我需要检索location_id,它的maxcontent_likes按国家顺序按sumcontent_likes desc分组 现在我得到的是基于国家的正确数据,但是我得到的Id是默认顺序。但我需要得到的不是默认的有序id,而是具有最大喜欢度的id 我现在的问题是Mysql 我的sql get id,它具有按列分组并按总和排序的最大喜欢数(喜欢数),mysql,sql,Mysql,Sql,我需要从视图中检索数据。视图将包含诸如国家、位置、内容、url、内容和。。。。我需要检索location_id,它的maxcontent_likes按国家顺序按sumcontent_likes desc分组 现在我得到的是基于国家的正确数据,但是我得到的Id是默认顺序。但我需要得到的不是默认的有序id,而是具有最大喜欢度的id 我现在的问题是 select * from <view_name> group by country order by sum(content_likes)
select * from <view_name> group by country order by sum(content_likes) desc;
来自视图的数据:
结果:
你似乎想要这样的东西:
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
);
如果出现语法错误,您可以尝试以下操作:
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
这是两遍查询,但请给出示例结果。如果多个位置具有相同的喜欢次数,并且这些是该国家/地区的最大喜欢次数,则可以为该国家/地区返回多行
希望这对您有所帮助。我的问题用下面的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
select*with group by表明对SQL的工作方式缺乏了解。您应该提供示例数据和期望的结果。感谢我使用mysql服务器的回复。mysql服务器中不支持排名。你能提供其他的建议吗?我不是mysql的专家。。。也许你可以使用这个工作区:请用你最新的例子回顾编辑过的答案。我应用了这个查询,但得到了相同的结果。