2015-05-11 56 views
1

假設在Oracle中有一個名爲DISTANCES的表,名爲distance的浮點類型列。距離範圍是[0,1000]。我想知道距離的分佈,例如,在以下每個範圍中有多少行:[0,10],(10,50),(50,100],(100,500),.. 。?(5000,10000]如何在Oracle中查詢列值的分佈(按值範圍分組)?

如何建立這個SQL查詢

+0

請顯示你的表的完整定義(最好是'create table') –

回答

3

使用派生表把每個距離到它的組,然後GROUP BYcount

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 
+0

你的sql完美地工作。一個更進一步的問題ñ,如果我想知道每個組在同一時間的百分比,該怎麼辦? –

+0

我不是Oracle用戶,但我認爲他們有很好的功能。無論如何,在ANSI SQL中,您可以簡單地將「count(*)* 100.0 /(從距離中選擇count(*))」添加到選擇列表中。 – jarlh

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;