0

我有一个存储金额和利率的表格,看起来像这样。这些实际上是对我正在构建的一个简单系统的贷款的出价或出价。如果有 1000000 英镑的贷款,则该贷款可以有多个要约/投标。

我需要根据最佳利率对这些出价进行排序,这是我可以做到的。但是,我无法保持运行总数来跟踪哪些出价是可以接受的。

这是我的桌子。

+-----+--------+---------------+------------+
| id  | amount | interest_rate | aggregated |
+-----+--------+---------------+------------+
| 105 | 100000 | 5             |     100000 |
| 108 | 500000 | 6.75          |     600000 |
| 107 |  50000 | 7             |     650000 |
| 106 | 100000 | 8             |     750000 |
| 112 | 500000 | 8.75          |    1250000 |
| 111 |   5000 | 16            |    1255000 |
| 110 | 500000 | 20            |    1755000 |
+-----+--------+---------------+------------+

在这里你可以看到我已经设法得到一个聚合列。但是,我需要获得所有低于 1000000 英镑的出价,这意味着如果我使用聚合列,它只会返回前四名。

为了给您一个更好的主意,这里再次列出了我需要的所需返回结果的表格。

+-----+--------+---------------+------------+--------+--------+
| id  | amount | interest_rate | aggregated | wanted | total  |
+-----+--------+---------------+------------+--------+--------+
| 105 | 100000 | 5             |     100000 | *      | 100000 |
| 108 | 500000 | 6.75          |     600000 | *      | 600000 |
| 107 |  50000 | 7             |     650000 | *      | 650000 |
| 106 | 100000 | 8             |     750000 | *      | 750000 |
| 112 | 500000 | 8.75          |    1250000 |        | 750000 |
| 111 |   5000 | 16            |    1255000 | *      | 755000 |
| 110 | 500000 | 20            |    1755000 |        | 755000 |
+-----+--------+---------------+------------+--------+--------+

基本上,我想选择所有按interest_rate 排序且小于1000000 的行。您可以在这里看到我们跳过了第112 行,因为750000 + 1250000 > 1000000,因此我们跳过它并继续前进。

这是我目前用来返回这些结果的简单 SQL。

SET @aggregated = 0;
SET @position = 0;
SELECT id, amount, interest_rate, aggregated FROM (
    SELECT 
        *,
        @aggregated := @aggregated + `auction_bids`.`amount` as `aggregated`,
        @position := @position + 1 as `position`        
    FROM 
        `auction_bids` 
    WHERE 
        `auction_bids`.`auction_id` = 21 AND
        `auction_bids`.`amount` < 1000000
    ORDER BY 
        `auction_bids`.`interest_rate` ASC
) as `a`;
4

1 回答 1

0

这可能会有所帮助,尽管当我尝试在 SQLFiddle 上的嵌套查询中使用它时出错:

set @aggregated := 0;
set @position := 0;
set @inc := 0;

select
    *,
    @aggregated := @aggregated + `auction_bids`.`amount` as `aggregated`,
    @position := @position + 1 as `position`,
    case 
        when @inc + `auction_bids`.`amount` <= 1000000 then 1
        else 0 
    end as `wanted`,
    @inc := @inc + case 
        when @inc + `auction_bids`.`amount` > 1000000 then 0 
        else `auction_bids`.`amount` 
    end as `includedaggregate`
from
    `auction_bids` 
where 
    `auction_bids`.`auction_id` = 21 and
    `auction_bids`.`amount` < 1000000
order by
    `auction_bids`.`interest_rate`

Example SQLFiddle

于 2013-10-27T21:35:37.487 回答