如果有很多数据点,您还可以像这样将范围分组在一起:
SELECT FLOOR(grade/5.00)*5 As Grade,
COUNT(*) AS [Grade Count]
FROM TableName
GROUP BY FLOOR(Grade/5.00)*5
ORDER BY 1
此外,如果您想标记整个范围,您可以使用 CTE 提前获得地板和天花板。
With GradeRanges As (
SELECT FLOOR(Score/5.00)*5 As GradeFloor,
FLOOR(Score/5.00)*5 + 4 As GradeCeiling
FROM TableName
)
SELECT GradeFloor,
CONCAT(GradeFloor, ' to ', GradeCeiling) AS GradeRange,
COUNT(*) AS [Grade Count]
FROM GradeRanges
GROUP BY GradeFloor, CONCAT(GradeFloor, ' to ', GradeCeiling)
ORDER BY GradeFloor
注意:在某些 SQL 引擎中,您可以GROUP BY
使用序数列索引,但对于 MS SQL,如果您希望在SELECT
语句中使用它,您还需要按它进行分组,因此也将范围复制到组表达式中。
选项 2:您可以使用case 语句有选择地将值计数到任意 bin 中,然后对它们进行 unpivot以获得包含值的逐行计数