MYSQL多组by和max
这是一张名为posts_vots的表格MYSQL多组by和max,mysql,sql,sum,max,Mysql,Sql,Sum,Max,这是一张名为posts_vots的表格 id|discussion_id|post_id|user_id|vote_sign| __________________________________________ 1 | 1 | 1 | 1 | 1 | 2 | 1 | 1 | 2 | -1 | 3 | 1 | 2 | 3 | 1 | 4 | 1
id|discussion_id|post_id|user_id|vote_sign|
__________________________________________
1 | 1 | 1 | 1 | 1 |
2 | 1 | 1 | 2 | -1 |
3 | 1 | 2 | 3 | 1 |
4 | 1 | 2 | 4 | 1 |
5 | 2 | 3 | 1 | -1 |
6 | 2 | 4 | 2 | 1 |
我想用这些结果创建一个视图:
discussion_id|post_id|score
1 | 2 | 2
2 | 4 | 1
与:
- post_id是得分最高的帖子
- 分数是总和(投票号)
谢谢;)首先使用子查询计算分数并为每个讨论id选择最大分数。然后
加入结果集以获得每个讨论id的最大分数的帖子
select t1.*
from (select discussion_id,post_id,sum(vote_sign) as score
from posts_votes
group by discussion_id,post_id) t1
join (select discussion_id,max(score) as maxscore
from (select discussion_id,post_id,sum(vote_sign) as score
from posts_votes
group by discussion_id,post_id) t
group by discussion_id) t2
on t1.discussion_id = t2.discussion_id and t1.score = t2.maxscore
这里是与您的问题相对应的查询
select
discussion_id,
max(post_id) as max_post_id,
sum(vote_sign) as score
from
posts_votes
group by
discussion_id;
这恰好为示例数据提供了正确的解决方案,但是max(post_id)并不总是返回正确的post。是的。这是必需的@草莓..如果使用其他支持窗口功能的dbms,它会更容易。耶!非常感谢。这很好,只有当两个项目的分数相同时才有缺点,但我会用代码来处理它!
select
discussion_id,
max(post_id) as max_post_id,
sum(vote_sign) as score
from
posts_votes
group by
discussion_id;
select SUBSTRING_INDEX(GROUP_CONCAT(post_id ORDER BY sm DESC), ',', 1) AS top_post, discussion_id, max(score) as score
from (
select discussion_id, post_id, sum(vote_sign) as score
from posts_votes
group by post_id, discussion_id
) c
group by discussion_id