简体   繁体   中英

SQL - Select number of record based on SUM conditions

if you have a order table, is that possible to select all the records which have sum of amount smaller than $1000, assuming that the table already ordered by amount desc Example:

id product_id amount
1  1          500
2  3          400
3  2          300
4  1          200

Get all the orders which have sum of amount smaller than $1000 then it should return 1 & 2, because the sum of amount of 1 and 2 is 900 < 1000

Get all the orders which have sum of amount smaller than $1300 then it should return 1,2,3 because the sum of amount of 1,2,3 is 1200 < 1300

You are looking for a cumulative sum:

select t.*
from (select t.*, sum(t.amount) over (order by t.amount desc) as cume_amount
      from t
     ) t
where cume_amount < 1000;
with a as ( 
    select  sum(amount) over (order by amount desc ) as amount_1 from test_order
)
select * from a where amount_1 < 1000;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM