如何根据平均计算对mysql查询结果进行分组?

时间:2017-03-18 19:46:37

标签: mysql sql average

我试图根据他们的AVG(正面投票 - 否定投票)有多好来展示我的帖子评论...但是我在尝试构建查询时感到困惑去做。我需要将它们显示为:最初的AVG,最后是最坏的AVG,就像后代一样。

这是我用来执行此操作的查询:

SELECT c.user AS user, DATE_FORMAT(c.date,'%d de %b a las %h:%i %p') AS datee, c.comment AS comment, COUNT(DISTINCT l.id_like) AS likes, COUNT(DISTINCT d.id_dislike) AS dislikes, AVG(likes - dislikes) AS avg  FROM comments c LEFT JOIN likes l ON l.id_comment=c.id_comment LEFT JOIN dislikes d ON c.id_comment=d.id_comment  WHERE c.id_post= ? AND l.id_like > 0 GROUP BY c.id_comment DESC LIMIT 10

但是没有像我想的那样工作

1 个答案:

答案 0 :(得分:0)

如果将计算视为差异而不是平均值,也许会有所帮助:

SELECT c.user AS user,
       DATE_FORMAT(c.date,'%d de %b a las %h:%i %p') AS datee,
       c.comment AS comment,
       COUNT(DISTINCT l.id_like) AS likes,
       COUNT(DISTINCT d.id_dislike) AS dislikes,
       (COUNT(DISTINCT l.id_like) - COUNT(DISTINCT d.id_dislike)) as Difference
FROM comments c LEFT JOIN
     likes l
     ON l.id_comment = c.id_comment LEFT JOIN
     dislikes d
     ON c.id_comment = d.id_comment 
WHERE c.id_post= ? AND l.id_like > 0
GROUP BY c.user, datee, c.id_comment DESC
ORDER BY Difference DESC
LIMIT 10;