【问题标题】:Select rows until to amount选择行直到达到金额
【发布时间】:2023-04-01 04:46:01
【问题描述】:

我需要选择第一行(按日期排序),直到例如。价格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

提前致谢。

【问题讨论】:

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


    【解决方案1】:

    试试这个:

    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
    

    【讨论】:

    • 我稍微修改一下,因为查询不包括最后一条记录。 WHERE o.totalPrice
    【解决方案2】:
    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 |
    +----+-------+-------+---------------------+
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 2013-01-08
      • 1970-01-01
      • 2014-02-02
      • 2012-10-21
      • 1970-01-01
      相关资源
      最近更新 更多