I have a table with id
, cost
, and priority
columns:
create table a_test_table (id number(4,0), cost number(15,2), priority number(4,0));
insert into a_test_table (id, cost, priority) values (1, 1000000, 10);
insert into a_test_table (id, cost, priority) values (2, 10000000, 9);
insert into a_test_table (id, cost, priority) values (3, 5000000, 8);
insert into a_test_table (id, cost, priority) values (4, 19000000, 7);
insert into a_test_table (id, cost, priority) values (5, 20000000, 6);
insert into a_test_table (id, cost, priority) values (6, 15000000, 5);
insert into a_test_table (id, cost, priority) values (7, 2000000, 4);
insert into a_test_table (id, cost, priority) values (8, 3000000, 3);
insert into a_test_table (id, cost, priority) values (9, 3000000, 2);
insert into a_test_table (id, cost, priority) values (10, 8000000, 1);
commit;
select
id,
to_char(cost, '$999,999,999') as cost,
priority
from
a_test_table;
ID COST PRIORITY ---------- ------------- ---------- 1 $1,000,000 10 2 $10,000,000 9 3 $5,000,000 8 4 $19,000,000 7 5 $20,000,000 6 6 $15,000,000 5 7 $2,000,000 4 8 $3,000,000 3 9 $3,000,000 2 10 $8,000,000 1
Starting with the highest priority (descending), I want to select the rows where the cost
adds up to less than (or equal to) $20,000,000.
The result would look like this:
ID COST PRIORITY
---------- ------------- ----------
1 $1,000,000 10
2 $10,000,000 9
3 $5,000,000 8
7 $2,000,000 4
Total: $18,000,000
How can I do this with Oracle SQL?