Query to get all records until the sum of column less than or equal a value

≯℡__Kan透↙ 提交于 2021-02-20 00:39:37

问题


I want to get all the records in a table until the sum of a particular column is less than or equal to 'n'.

For example:

Table: data

slno     item       price

1        item1      1000
2        item2      2000
3        item3      3000
4        item4      4000
5        item5      5000
6        item6      6000

I want to get all records from above table until the sum(price) is less than or equal to 10000

So, with the above table my result would be first 4 records.


回答1:


You can do

SELECT slno, item, price
  FROM
(
  SELECT slno, item, price, @t := @t + price total
    FROM table1 CROSS JOIN (SELECT @t := 0) i
   ORDER BY slno
) q
 WHERE total <= 10000

or

SELECT slno, item, price
  FROM
(
  SELECT slno, item, price, 
  (
    SELECT SUM(price)
      FROM table1
     WHERE slno <= t.slno
  ) total
    FROM table1 t
) q
 WHERE total <= 10000
 ORDER BY slno

Here is SQLFiddle demo



来源:https://stackoverflow.com/questions/21824383/query-to-get-all-records-until-the-sum-of-column-less-than-or-equal-a-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!