2

我正在尝试按它们所在的范围对表中的值进行存储,例如,如果我的表如下:

course_name | current enrollment
course_1    | 10
course_2    | 200
course_3    | 500

我得到以下结果:

enrollment_range | courses
10               | 1
100              | 1
500              | 1

到目前为止,我有以下内容:

SELECT 
  CASE
    WHEN courses.current_enrollment >= 500 THEN 500
    WHEN courses.current_enrollment >= 250 THEN 250
    WHEN courses.current_enrollment >= 100 THEN 100
    WHEN courses.current_enrollment >= 50 THEN 50
    WHEN courses.current_enrollment >= 30 THEN  30
    WHEN courses.current_enrollment >= 10 THEN 10
  END enrollment_range, count() AS total
FROM courses
GROUP BY enrollment_range
ORDER BY enrollment_range ASC

但我最终得到了一个额外的结果,即我所拥有的课程总数,所以我得到如下内容:

enrollment_range | courses
10               | 1
100              | 1
500              | 1
                 | 3
4

2 回答 2

0

额外的结果是不属于指定括号的课程数量,在这种情况下,注册人数低于 10 的课程。

于 2017-06-08T20:22:07.287 回答
0

在您的 sql 中,您应该在计数中使用一个组。在我的 SQL 服务器中,我可以使用以下脚本生成正确的结果:

SELECT 
  CASE
    WHEN current_enrollment >= 500 THEN 500
    WHEN current_enrollment >= 250 THEN 250
    WHEN current_enrollment >= 100 THEN 100
    WHEN current_enrollment >= 50 THEN 50
    WHEN current_enrollment >= 30 THEN  30
    WHEN current_enrollment >= 10 THEN 10
  END as enrollment_range, t.course_name, t.count
FROM courses 

join 
( select  Count(course_name) as count,course_name FROM courses group by course_name ) t

on courses.course_name = t.course_name
于 2017-06-08T20:10:49.817 回答