我看过几个地方,也许我只是没有正确地措辞搜索。我发现了类似的问题,但没有一个回答这个问题。
我有一张 Sight Inventories 表(用户在该表中走过存储区并实际检查手头有多少产品)。该表处理多个位置。表结构(部分,仅需要的信息)为:
create table location_inventory (
id int unsigned not null auto_increment,
location_id int unsigned references location(location_id),
inventory_item_id int unsigned references inventory_item (inventory_item_id),
inventory_date date comment 'Date the sight inventory was taken',
quantity decimal( 15,2 ) comment 'Number of items found during inventory',
primary key ( id ),
unique (location_id,inventory_item_id,inventory_date)
);
它应该是以下形式的查询:
select
a.location_id location,
a.inventory_item_id inventory_item,
a.inventory_date curr_date,
a.quantity curr_quant,
b.inventory_date prev_date,
b.quantity prev_quant,
a.quantity - b.quantity num_used
from
location_inventory a
left outer join
(
select
location_id,
inventory_item_id,
inventory_date,
quantity
from
location_inventory
where
something
) b
on ( location_id,inventory_item_id )
where
a.inventory_date between DATEA and DATEB
但我还没有让它工作。
我缺少的是整个子查询。我已经看到了几个我们得到上一个日期的答案,但是没有一个我可以真正从上一行中检索其余值的答案;它最终检索整个表中最新条目的值。