范围

时间:2015-09-09 10:56:08

标签: php mysql

我有一个评级表,其中包含2个字段RatingID,UserID,RateValue RateValue可以是2位十进制

我想要的是按结果在RateValue和Count Records的范围之间进行分组,例如

0-1.5之间的RateValue应该返回1,1.6-2.5将是2,2.6-3.5将是3,3.6-4.5将是4,4.6-5将是5

我想在该范围之间进行分组,并获得

之类的结果

OneStarRating - 2 TwoStarRating - 0 ThreeStarRating - 3 FourStarRating - 1 FiveStarRating - 6

我现在尝试的是这个但不起作用

SELECT COUNT(RatingID) as TotalRecords, (IF(RateValue BETWEEN 0 AND 1.5,"OneStarRating",false) OR IF(RateValue BETWEEN 1.6 and 2.5,"TwoStarRating",false) OR IF(RateValue BETWEEN 2.6 and 3.5,"ThreeStarRating",false) OR IF(RateValue BETWEEN 3.6 and 4.5,"FourStarRating",false) OR IF(RateValue BETWEEN 4.6 and 5,"FiveStarRating",false)) as RateValue
FROM (`Ratings`)
GROUP BY RateValue

4 个答案:

答案 0 :(得分:1)

可能有一个联合查询的子查询,以恢复您感兴趣的范围: -

SELECT sub0.RateValue, COUNT(RatingID)
FROM Ratings
INNER JOIN
(
    SELECT 0 AS low_bound, 1.5 AS high_bound, "OneStarRating" AS RateValue
    UNION SELECT 1.6, 2.5, "TwoStarRating"
    UNION SELECT 2.6, 3.5, "ThreeStarRating"
    UNION SELECT 3.6, 4.5, "FourStarRating"
    UNION SELECT 4.6, 5, "FiveStarRating"
) sub0
ON Ratings.RateValue BETWEEN sub0.low_bound AND sub0.high_bound
GROUP BY sub0.RateValue

编辑 - 要在没有记录的情况下获得0的计数: -

SELECT sub0.RateValue, COUNT(RatingID)
FROM
(
    SELECT 0 AS low_bound, 1.5 AS high_bound, "OneStarRating" AS RateValue
    UNION SELECT 1.6, 2.5, "TwoStarRating"
    UNION SELECT 2.6, 3.5, "ThreeStarRating"
    UNION SELECT 3.6, 4.5, "FourStarRating"
    UNION SELECT 4.6, 5, "FiveStarRating"
) sub0
LEFT OUTER JOIN Ratings
ON Ratings.RateValue BETWEEN sub0.low_bound AND sub0.high_bound
GROUP BY sub0.RateValue

答案 1 :(得分:0)

您可以使用case语句(或一堆凌乱的if)。但是,round()可能足以满足您的需求:

select round(RateValue) as rounded_ratevalue, count(*)
from ratings
group by rounded_ratevalue
order by rounded_ratevalue;

答案 2 :(得分:0)

这适合你吗?

SELECT COUNT(RatingID) as TotalRecords, 
CASE WHEN `RateValue` BETWEEN 0 AND 1.5   THEN "OneStarRating"
 WHEN `RateValue` BETWEEN 1.6 AND 2.5 THEN "TwoStarRating"
 WHEN `RateValue` BETWEEN 2.6 AND 3.5 THEN "TreeStarRating"
 WHEN `RateValue` BETWEEN 3.6 AND 4.5 THEN "FourStarRating"
 WHEN `RateValue` BETWEEN 4.6 AND 5.5 THEN "FiveStarRating"
 ELSE "NotRated"
END AS RatedValue
FROM `Ratings`
GROUP BY RatedValue

答案 3 :(得分:0)

试一试 -

SELECT COUNT(ratevalue) AS TotalRecords, 
CASE WHEN ratevalue>= 0 AND ratevalue<= 1.5 THEN 'OneStarRating' WHEN ratevalue> 1.5 AND ratevalue<= 2.5 THEN 'TwoStarRating' WHEN ratevalue> 2.5 AND ratevalue<= 3.5 THEN 'ThreeStarRating' WHEN ratevalue> 3.5 AND ratevalue<= 4.5 THEN 'FourStarRating' WHEN ratevalue> 4.5 AND ratevalue<= 5 THEN 'FiveStarRating' ELSE 'None' END AS RateValue 
FROM Ratings 
GROUP BY RateValue;