您似乎想要创建结果的直方图。
PostgreSQL:
select x, count(val)
from generate_series(1,6) x
left outer join numbers on (x = width_bucket(val, 0, 60, 6))
group by x;
我使用width_bucket
了而不是简单的除法和模数,因为它更通用,更容易正确处理更复杂的范围。此外,它太棒了。
如果您愿意,可以集成和加入 Mark Bannister 用于序列生成的递归 CTE,x
而不是generate_series
增加可移植性,并且可以自动确定限制:
with recursive ranges(rangev) as (
select 0 rangev union all select rangev+1 as rangev from ranges where rangev < 4
), bounds(lower_bucket, upper_bucket) as (
select (min(val))/10, (max(val)/10)+1 from numbers
)
select
rangev as bucket,
rangev*10 AS lower_bound,
(rangev+1)*10-1 AS upper_bound,
count(val) AS num_in_bucket
from ranges cross join bounds
left outer join numbers on (rangev = width_bucket(val, lower_bucket, upper_bucket*10, upper_bucket))
group by rangev
order by rangev asc;
如果您更喜欢/10
(width_bucket
例如,如果width_bucket
在 MS SQL 中不可用),那很容易改回来。
输出:
bucket | lower_bound | upper_bound | num_in_bucket
--------+-------------+-------------+---------------
0 | 0 | 9 | 0
1 | 10 | 19 | 2
2 | 20 | 29 | 3
3 | 30 | 39 | 0
4 | 40 | 49 | 1
(5 rows)