我需要根据列qty
例如,这是我的数据库
| id | qty | wh | car |
-----------------------
| x1 | 2 | a | z |
| x2 | 3 | b | y |
| x3 | 10 | a | z |
| x4 | 5 | a | z |
| x5 | 2 | b | z |
| x6 | 2 | a | z |
| x7 | 3 | a | z |
这是我的疑问:
SELECT * FROM table WHERE wh = 'a' AND car = 'z' ORDER BY qty LIMIT sum(qty) <= 20
因此我需要得到:
| id | qty | wh | car |
-----------------------
| x3 | 10 | a | z |
| x4 | 5 | a | z |
| x7 | 3 | a | z |
| x1 | 2 | a | z |
我想我可能需要使用子查询?
答案 0 :(得分:2)
您可以尝试此查询,首先将一个数字作为ID rn
,然后累加两个数据集,判断大于20
SELECT t1.id,t1.qty,t1.wh,t1.car
FROM (
select t.*,(@rn:=@rn+1) rn
from
(
SELECT *
FROM T
WHERE wh = 'a' AND car = 'z'
ORDER BY qty asc
) t CROSS JOIN (select @rn:=0) a
)t1 CROSS JOIN
(
select t.*,(@rn1:=@rn1+1) rn
from
(
SELECT *
FROM T
WHERE wh = 'a' AND car = 'z'
ORDER BY qty asc
) t CROSS JOIN (select @rn1:=0) a
)t2
WHERE t1.rn < t2.rn + 1
group by t1.id,t1.qty
HAVING sum(t2.qty) <= 20
ORDER BY t1.qty DESC
sqlfiddle:http://sqlfiddle.com/#!9/22740/6