对于SQL查询,使用where子句计数错误

时间:2015-05-03 20:09:00

标签: mysql sql

在mysql数据库中,我有一个这样的表:

create table review(
reviewId varchar(12) primary key,
helpfulness double,
reviewRating integer)

我尝试计算有用且无用的group by reviewRatinghelpfulness where> = 0.75作为无益或其他< 0.75作为乐于助人。我怎么能得到这样的结果?

unhelpfulness helpfulness reviewRating
5             2           1
4             2           2 
3             4           3
  

我试图这样做,但似乎计数不起作用,加入在该位置无效。

SELECT a.count AS HELPFUL, b.count AS UNHELPFUL 
FROM review a where helpfulness>=0.75 group by a.reviewRating
OUTER JOIN review b where helpfulness<0.75 group by b.reviewRating
on a.reviewRating = b.reviewRating

2 个答案:

答案 0 :(得分:3)

在Mysql中,您可以使用sum使用某些条件或表达式来生成布尔值(0/1),这样就可以得到条件计数

SELECT a.reviewRating,
SUM(helpfulness>=0.75) AS HELPFUL,
SUM(helpfulness < 0.75)AS UNHELPFUL 
FROM review a 
GROUP BY a.reviewRating

答案 1 :(得分:0)

您可以使用case表达式实现条件聚合:

select a.reviewRating
     ,  count(case when helpfulness >= 0.75 then helpfulness end) as helpful
     ,  count(case when helpfulness < 0.75 then helpfulness end) as unhelpful 
from review a 
group by a.reviewRating