fifo_cost
との差に基づいて、特定の注文に権利を割り当てようとしています。 と の最小の差に関連付けられfifo_in_date
ている をその注文に割り当てる必要があります。order_date
fifo_cost
order_date
fifo_date_in
次の mysql スニペットはレコードを返しません。fifo_date_in
に最も近い1 つのレコードが返されることを期待していますorder_date
が、明らかに何かが欠けています。
drop table if exists tmp;
create table tmp (
order_sequence int,
order_number int,
order_date date,
fifo_date_in date,
fifo_cost float);
INSERT INTO tmp (order_sequence, order_number, order_date, fifo_date_in, fifo_cost) VALUES (5613, 561, '2013-01-02','2009-01-01',1.55);
INSERT INTO tmp (order_sequence, order_number, order_date, fifo_date_in, fifo_cost) VALUES (5613, 561, '2013-01-02','2009-02-01',2.55);
INSERT INTO tmp (order_sequence, order_number, order_date, fifo_date_in, fifo_cost) VALUES (5613, 561, '2013-01-02','2009-03-01',3.55);
INSERT INTO tmp (order_sequence, order_number, order_date, fifo_date_in, fifo_cost) VALUES (5613, 561, '2013-01-02','2009-04-01',4.55);
INSERT INTO tmp (order_sequence, order_number, order_date, fifo_date_in, fifo_cost) VALUES (5613, 561, '2013-01-02','2009-05-01',5.55);
SELECT
order_sequence, order_number, order_date, fifo_date_in, fifo_cost, datediff(order_date,fifo_date_in) as ddiff
FROM tmp
GROUP BY order_sequence, order_number, order_date
HAVING datediff(order_date,fifo_date_in) = min(datediff(order_date,fifo_date_in))