假设Oracle中有一个名为DISTANCES的表,其中一个名为distance的浮点类型列。距离范围为[0,1000]。我想知道距离的分布,例如,以下每个范围中有多少行:(0,10),(10,50),(50,100),(100,500),... 。(5000,10000)。
如何构建此SQL查询?
答案 0 :(得分:4)
使用派生表将每个距离放入其组中。然后GROUP BY
和count
:
select dist_group, count(*)
from
(
select case when distance between 0 and 10 then '(0, 10)'
when distance between 10 and 50 then '(10, 50)'
...
when distance between 5000 and 10000 then '(5000, 10000)' end as dist_group
from distances
)
group by dist_group
答案 1 :(得分:3)
SELECT COUNT( CASE WHEN 0 <= distance AND distance <= 10 THEN distance END ) AS in_range_0_10,
COUNT( CASE WHEN 10 < distance AND distance <= 50 THEN distance END ) AS in_range_10_50,
COUNT( CASE WHEN 50 < distance AND distance <= 100 THEN distance END ) AS in_range_50_100,
COUNT( CASE WHEN 100 < distance AND distance <= 500 THEN distance END ) AS in_range_100_500,
COUNT( CASE WHEN 500 < distance AND distance <= 1000 THEN distance END ) AS in_range_500_1000
FROM Distance;