表格订单:
id month price
--------------------------------------
1 12 74.00
2 11 27.00
3 12 35.00
4 12 85.00
5 12 38.00
6 04 45.00
7 03 27.00
8 12 23.00
9 12 45.00
10 03 36.00
11 12 67.00
12 06 45.00
13 12 23.00
14 12 35.00
如何从月份= 12且所选行数总和小于150且大于100的订单中选择随机行?
或总和最多为150 ......
期望的结果之一(总和147.00):
id month price
--------------------------------------
1 12 74.00
5 12 38.00
14 12 35.00
其他所需结果的例子(总和131.00):
id month price
--------------------------------------
3 12 35.00
5 12 38.00
8 12 23.00
14 12 35.00
我试过这样的事情,但没有成功:
SELECT id,month,price,SUM(price)
FROM orders
WHERE month = '12' AND SUM(price) < 150 AND SUM(price) > 100
ORDER BY rand()
请帮帮我
答案 0 :(得分:0)
这是一个复杂的问题。您需要对随机行执行累积求和,然后选择任意值。
这会使你的限制低于150:
SELECT o.*
FROM (SELECT o.*, @cumep := (@cum3p + price) as cumep
FROM orders o CROSS JOIN (SELECT @cumep := 0) params
WHERE month = 12
ORDER BY rand()
) o
WHERE cumep < 150;