2015-01-01 62 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小提琴,因为它似乎今天被打破。