我正在尝试根据和之间的差异为给定订单分配权利:fifo_cost
关联到和之间的最小差异应该分配给该订单。fifo_in_date
order_date
fifo_cost
order_date
fifo_date_in
以下 mysql 片段不会返回任何记录。我希望它能够返回fifo_date_in
最接近 的记录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))