通过值的总和限制查询

时间:2015-10-24 03:49:58

标签: mysql sql

我有一个mysql表,交易,有字段id,transactionType,数量,价格等。我想通过一列的累积总和来限制记录。所以我想拉出所有交易,直到累积数量达到我的变量(此处< = 50)。

我做错了什么?

SET @qsum := 0; 
SELECT * 
FROM (
  SELECT *, (@qsum := @qsum + quantity) AS cumulative_quantity 
  FROM transactions ORDER BY id DESC
) transactions 
WHERE 
transactionType = 'buy'
AND typeID = 10
AND cumulative_quantity <= 50

1 个答案:

答案 0 :(得分:0)

试试这种方式

SET @qsum := 0; 
SELECT * 
FROM (
  SELECT *, (@qsum := @qsum + quantity) AS cumulative_quantity 
  FROM transactions
  WHERE transactionType = 'buy'
   AND typeID = 10
   AND cumulative_quantity <= 50
  ORDER BY id DESC
) transaction