RE:如何制作这个sql。 (条件sql)

时间:2010-09-30 05:11:45

标签: sql mysql

我在这里质疑: How make this sql. ( conditions sql )

但现在,我想要

SELECT SUM( Post.rating ) as countRating <--- THIS i want Post.rating * 5 WHEN Post.recommended = 1
FROM posts as Post
ORDER BY countRating DESC

帮帮我

1 个答案:

答案 0 :(得分:2)

基本上,使用与其他问题的答案相同的技术 - 使用CASE表达式,这次是在SUM中而不是在ORDER BY子句中。

SELECT SUM(CASE Recommended WHEN 1 THEN 5 ELSE 1 END * Rating) AS countRating
  FROM posts as Post
 ORDER BY countRating DESC

如果推荐的替代值为0(似乎合理的猜测),那么您也可以写:

SELECT SUM((4 * Recommended + 1) * Rating) AS countRating
  FROM posts as Post
 ORDER BY countRating DESC

事实上,你可以对上一个问题中的ORDER BY子句做同样的事情。