从 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 Fiddle,因为它今天似乎坏了。