问题
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