如何从具有限制SUM值列的数据库中进行记录

时间:2017-07-21 11:56:55

标签: php mysql

我有一些客户发票的表格。我需要返回SUM(price)小于 200美元的记录,这意味着返回记录直到总计或sum invoice price < 200$

有时我希望返回最新的记录,有时从一开始。 我使用MYSQL数据库和php。

table
-----------------------
id | customerId | price
1         20        15
2         15        10
3         65        42
4         44        12
5         23        78
6         11        66
7         16        95
8         33        48

3 个答案:

答案 0 :(得分:2)

我会建议用于计算累积和的变量:

select t.*
from (select t.*, (@s := @s + price) as sum_price
      from t cross join
           (select @s := 0) params
      order by id
     ) t
where sum_price < 200;

答案 1 :(得分:0)

让HAVING过滤你的结果&lt; 200:

SELECT SUM(price) as total, customerId
FROM table
GROUP BY customerId
HAVING total < 200

修改

所以你不需要客户,而是需要他的所有记录:然后使用上面的查询作为子查询:

SELECT maintable.Id, maintable.customerId, maintable.price
FROM table AS maintable 
JOIN (
   SELECT  customerId
   FROM table
   GROUP BY customerId
   HAVING SUM(price) < 200
) subq ON subq.customerId = maintable.customerId

答案 2 :(得分:0)

client

此查询计算并返回总数小于200的行。