[英]How to select random rows where the rows sum price is less than 500 and greater than 450?
Table orders: 表订单:
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
How to select random rows from orders where month = 12 and sum of selected rows is less than 150 AND greater than 100 ? 如何从月份= 12并且所选行的总和小于150并且大于100的订单中选择随机行?
or that the sum is max 150... 或总和最大为150 ...
One of the desired results (sum 147.00): 期望的结果之一(总和147.00):
id month price
--------------------------------------
1 12 74.00
5 12 38.00
14 12 35.00
example for other desired result (sum 131.00): 其他所需结果的示例(总和131.00):
id month price
--------------------------------------
3 12 35.00
5 12 38.00
8 12 23.00
14 12 35.00
I tried something like this, but unsuccessfully: 我尝试了类似的方法,但未成功:
SELECT id,month,price,SUM(price)
FROM orders
WHERE month = '12' AND SUM(price) < 150 AND SUM(price) > 100
ORDER BY rand()
please help me 请帮我
This is a complicated question. 这是一个复杂的问题。 You need to do a cumulative sum on the random rows and then choose an arbitrary value. 您需要对随机行进行累加和,然后选择一个任意值。
This gets you the limit of less than 150: 这使您的限制小于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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.