选择行直到达到金额

时间:2013-12-30 12:09:11

标签: mysql sql variables select sql-order-by

我需要选择第一行(按日期排序),直到例如。价格1500.我的桌子结构:

mysql> select * from offers;
+----+-------+-------+---------------------+
| id | name  | price | date                |
+----+-------+-------+---------------------+
|  1 | name1 |  1000 | 2013-12-28 11:00:00 |
|  2 | name2 |   800 | 2013-12-28 12:00:00 |
|  3 | name1 |   500 | 2013-12-28 13:00:00 |
|  4 | name1 |   500 | 2013-12-28 15:00:00 |
|  5 | name2 |  1000 | 2013-12-28 17:00:00 |
+----+-------+-------+---------------------+

在这种情况下,我需要选择记录1和2。

For example:
for $500 record 1
for $1100 records 1, 2
for $1800 records 1, 2
for $2200 records 1, 2, 3
for $2500 records 1, 2, 3, 4
for $10000 all available records

提前致谢。

2 个答案:

答案 0 :(得分:4)

试试这个:

SELECT o.id, o.name, o.price, o.date
FROM (SELECT o.id, o.name, o.price, o.date, (@totalPrice:=@totalPrice + o.price) totalPrice
      FROM offers o, (SELECT @totalPrice:=0) A
      ORDER BY o.date
     ) AS o
WHERE o.totalPrice <= 1500

答案 1 :(得分:0)

CREATE TABLE offers
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY 
,name VARCHAR(12) NOT NULL  
,price INT NOT NULL 
,date DATETIME               
);

INSERT INTO offers
VALUES
(1 ,'name1',1000,'2013-12-28 11:00:00'),
(2 ,'name2',800,'2013-12-28 12:00:00'),
(3 ,'name1',500 ,'2013-12-28 13:00:00'),
(4 ,'name1',500 ,'2013-12-28 15:00:00'),
(5 ,'name2',1000 ,'2013-12-28 17:00:00');

SELECT x.* 
  FROM offers x
  JOIN offers y
    ON y.date <= x.date
 GROUP 
    BY x.id
HAVING SUM(y.price) <= 1800
 ORDER 
    BY id DESC LIMIT 1;
+----+-------+-------+---------------------+
| id | name  | price | date                |
+----+-------+-------+---------------------+
|  2 | name2 |   800 | 2013-12-28 12:00:00 |
+----+-------+-------+---------------------+