Mysql

將行限制為列的總和等於某個值

  • October 10, 2017

我試圖將行限制為列的總和等於某個值,但我得到了意想不到的結果。

CREATE TABLE buy (
 id int not null,
 volume decimal(9,4) not null,
 price decimal(9,2) not null
);

insert buy (id, volume, price) values 
(1, 1.0000, 14250.00),
(2, 0.2500, 14251.10),
(3, 0.2500, 14250.00),
(4, 0.0050, 14200.00),
(5, 0.5000, 14255.01);

預期結果選擇了 ids 5,2,1(因為按最高價格排序),但它選擇了 ids 2,1,3

SELECT t.id, t.volume, t.price,
(SELECT SUM(volume) FROM buy WHERE id <= t.id) 'RequiredVolume'
FROM buy t
HAVING RequiredVolume <= '1.5000'
ORDER BY price DESC, id ASC;

| id | volume |   price | RequiredVolume |
|----|--------|---------|----------------|
|  2 |   0.25 | 14251.1 |           1.25 |
|  1 |      1 |   14250 |              1 |
|  3 |   0.25 |   14250 |            1.5 |

http://sqlfiddle.com/#!9/ef024/3/0

我認為問題可能是由於嵌套查詢>=而不是=.

這給出了您描述的輸出:

SELECT t.id, t.volume, t.price,
(SELECT SUM(volume) FROM buy WHERE id = t.id) 'RequiredVolume'
FROM buy t
HAVING RequiredVolume <= '1.5000'
ORDER BY price DESC, id ASC;

備忘錄 - 您能否發布您對所有欄位的預期結果,而不僅僅是 ID 排序。

我不是 MySQL 專家,但也許這對你有用,儘管它只會返回記錄 5 和 2,因為記錄 5、2 和 1 的滾動總和為 1.75,而不是你過濾的 1.5。

SELECT t.id, t.volume, t.price,
(SELECT SUM(volume) FROM buy WHERE (id <> t.id AND price > t.price) OR (id < t.id AND price = t.price) OR (id = t.id)) 'RequiredVolume'
FROM buy t
HAVING RequiredVolume <= 1.5
ORDER BY price DESC, id ASC;

這是帶有註釋的子句的SQLFiddle,以表明如果此邏輯確實是您所追求的,則只會返回記錄 5 和 2。HAVING

引用自:https://dba.stackexchange.com/questions/188096