我有两个表,我需要与他们建立多对多的关系。我们将称为库存的一个表格通过表格填充。通过每周将CSV导入数据库来填充其他表销售。
我想逐步浏览销售表,并将每个销售行与库存表中具有相同sku的行相关联。这是踢。我只需要关联每个Inventory行的Quantity字段中指示的销售行数。
示例:Example image of linked tables
现在我知道我可以通过创建一个perl脚本来执行此操作,该脚本遍历sales表并使用基于Quantity字段的循环中的ItemIDUniqueKey字段创建链接。我想知道的是,有没有办法单独使用SQL命令?我已经阅读了很多关于很多人的信息,而且我没有找到任何人这样做。
答案 0 :(得分:0)
假设表:
create table a(
item_id integer,
quantity integer,
supplier_id text,
sku text
);
和
create table b(
sku text,
sale_number integer,
item_id integer
);
以下查询似乎可以执行您想要的操作:
update b b_updated set item_id = (
select item_id
from (select *, sum(quantity) over (partition by sku order by item_id) as sum from a) a
where
a.sku=b_updated.sku and
(a.sum)>
(select count(1) from b b_counted
where
b_counted.sale_number<b_updated.sale_number and
b_counted.sku=b_updated.sku
)
order by a.sum asc limit 1
);