2015-01-01 61 views
0

我有一個作業表的列爲工資Rails SQL - 創建存儲桶,並獲得每個存儲桶中的記錄數

我怎樣才能將薪水分攤到$ 10,000的組中,然後獲得每個桶中有多少工作的計數?

使用Rails活動記錄的答案更可取,但考慮到困難,我也會接受原始SQL答案。

開始數據

Jobs 

id  salary (integer) 
----------------- 
1  93,530 
2  72,400 
3  120,403 
4  193,001 
... 

結果數據

bucket    job_count 
---------------------------- 
$0 - $9,999   0 
$10,000 - $19,999 0 
$20,000 - $29,999 3 
$30,000 - $39,999 5 
$40,000 - $49,999 12 

回答

0

這是另一種基於SQL的解決方案。

獲取桶每個工資這樣的:

select 
    FLOOR(salary/10000) as bucket 
from jobs 

使用GROUP BY做計數:

select 
    bucket, 
    count(*) 
from (
    select FLOOR(salary/10000) as bucket 
    from jobs 
) as t1 
GROUP BY bucket 

最後,添加範圍,而不是桶數目:

select 
    CONCAT('$', FORMAT(bucket*10000,0), ' - $', FORMAT((bucket+1)*10000-1,0)) as range, 
    job_count 
from ( 
    select bucket, count(*) as job_count 
    from (
     select FLOOR(salary/10000) as bucket 
     from jobs 
    ) as t1 
    GROUP BY bucket 
) as t2 

請注意,使用的功能是MySQL。因人而異。

+0

請注意,這可能會留下空的範圍。 – Turophile

0

從SQL角度來看有幾種方法。這是一個。

-- First, create a report table (temporarily here, but could be permanent): 

create table salary_report (
    bucket  integer, 
    lower_limit integer, 
    upper_limit integer, 
    job_count integer 
); 

-- populate the table 
-- note this could (and probably should) be automated, not hardcoded 
insert into salary_report values (1,00000,09999,0); 
insert into salary_report values (2,10000,19999,0); 
insert into salary_report values (3,20000,29999,0); 
insert into salary_report values (4,30000,39999,0); 
insert into salary_report values (5,40000,49999,0); 

-- set correct counts 
update salary_report as sr 
    set job_count = (
    select count(*) 
    from jobs as j 
    where j.salary between sr.lower_limit and sr.upper_limit 
    ); 

-- finally, access the data (through activerecord?) 
-- note: not formatted as dollar amounts 
select concat(sr.lower_limit,' - ',sr.upper_limit) as range, job_count, bucket 
from salary_report 
order by bucket; 

-- drop table if required 
drop table salary_report; 

我試圖保持SQL通用的,但確切的語法可能會根據您的RDBMS而有所不同。 沒有提供SQL小提琴,因爲它似乎今天被打破。