查询 table 并将结果分组到 Laravel 范围内

Query table and group results into ranges in Laravel

我有一个数据库table,存储了多条调查分数记录,分数在1-100之间。我试图通过将分数分组到以下范围内来在应用程序前端呈现频率分布;

因此,如果 table 具有数据 87、92、95、98,用户将看到

等我认为集合是实现它的方法,但我不知道从哪里开始获得这种输出,或者它是否可能 Laravel?

是的,这是可能的。我相信这是您需要的 SQL 查询(假设您的 table 名称是“scores”,而“score”是合适的字段):

select (case when score between 0 and 20 then 'Less than 20'
             when score between 21 and 30 then 'Between 21 and 30'
             when score between 31 and 40 then 'Between 31 and 40'
             when score between 41 and 50 then 'Between 41 and 50'
             when score between 51 and 60 then 'Between 51 and 60'
             when score between 61 and 70 then 'Between 61 and 70'
             when score between 71 and 80 then 'Between 71 and 80'
             when score between 81 and 90 then 'Between 81 and 90'
             when score between 91 and 100 then 'Between 91 and 100'
                 end) as score_range, count(*) as count
from scores
group by score_range
order by min(score);

所以对于 Laravel 它可以像这样工作:

$frequency = DB::select("SELECT (CASE
     WHEN score BETWEEN 0 AND 20 THEN 'Less than 20'
     WHEN score BETWEEN 21 AND 30 THEN '20-30'
     WHEN score BETWEEN 31 AND 40 THEN '30-40'
     WHEN score BETWEEN 41 AND 50 THEN '40-50'
     WHEN score BETWEEN 51 AND 60 THEN '50-60'
     WHEN score BETWEEN 61 AND 70 THEN '60-70'
     WHEN score BETWEEN 71 AND 80 THEN '70-80'
     WHEN score BETWEEN 81 AND 90 THEN '80-90'
     WHEN score BETWEEN 91 AND 100 THEN '90-100'
         END) AS score_range, COUNT(*) as count
    FROM scores
    GROUP BY score_range
    ORDER BY MIN(score);");

您可以只编辑文本标题。

在此查询中,“40-50”(例如)表示得分在 41 到 50 之间。如果需要,您也可以将“ORDER BY MIN(score)”替换为“ORDER BY count” .