我有一张存储金额和利率的表,看起来像这样。这些是有效的出价,或者是对我正在建设的简单系统贷款的贷款。如果有100万英镑的贷款,这笔贷款可以有多个要约/出价。
我需要按照最优惠利率对这些出价进行排序,我可以这样做。但是,我无法保持运行总计来跟踪哪些出价可以接受。
这是我的表格。
+-----+--------+---------------+------------+
| 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`;
答案 0 :(得分: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 强>