我有一个与我正在尝试编写的查询有关的非常具体的问题。
基本上,库存表有大约450,000行库存项目,显示每个月末每个库存项目的期末余额。其他表格包括一个发货表,用于跟踪进入和离开特定位置的所有库存物品的每日数据。然后我们还有一个生产表,用于跟踪每天在生产过程中使用的库存项目。
我们正在尝试使用运费和生产表创建另一个跟踪每周库存的表,然后计算月末差异。
这是我必须编写的脚本的伪代码:
FOR EACH ROW IN INVENTORY_TABLE
@incoming_shipping = SELECT INCOMING_AMOUNT FROM SHIPPING_TABLE WHERE WEEK_OF_MONTH = 1
@outgoing_shipping = SELECT OUTGOING_AMOUNT FROM SHIPPING_TABLE WHERE WEEK_OF_MONTH = 1
@outgoing_production =SELECT OUTGOING_AMOUNT FROM PRODUCTION TABLE WHERE WEEK_OF_MONTH = 1
@closing_inventory=ROW.OpeningAmount + @incoming_shipping - @outgoing_shipping + @outgoing_production
INSERT INTO WEEKLY_INVENTORY (Opening_Amount,Closing_Amount)
'Compute Week 2 Value
@incoming_shipping = SELECT INCOMING_AMOUNT FROM SHIPPING_TABLE WHERE WEEK_OF_MONTH = 2
@outgoing_shipping = SELECT OUTGOING_AMOUNT FROM SHIPPING_TABLE WHERE WEEK_OF_MONTH = 2
@outgoing_production =SELECT OUTGOING_AMOUNT FROM PRODUCTION TABLE WHERE WEEK_OF_MONTH = 2
@closing_inventory=ROW.OpeningAmount + @incoming_shipping - @outgoing_shipping + @outgoing_production
INSERT INTO WEEKLY_INVENTORY (Opening_Amount,Closing_Amount)
'Continue doing this for the Four, Maybe 5 weeks that occur in a month.
NEXT
虽然它是正确的,但查询是一个执行的噩梦,目前每分钟运行大约100行。我尝试过使用没有游标,游标等的循环,并且没有明显的性能差异。我想知道是否有更好的方法来编写脚本而不使用任何循环。
提前感谢您的帮助。
答案 0 :(得分:0)
我相信某些内容对您有用:
INSERT INTO WEEKLY_INVENTORY(Opening_Amount, Closing_Amount)
SELECT
OPENING_AMOUNT,
(OPENING_AMOUNT +
(SELECT INCOMING_AMOUNT
FROM SHIPPING_TABLE
WHERE WEEK_OF_MONTH = ST.WEEK_OF_MONTH)
) - (
(SELECT OUTGOING_AMOUNT
FROM SHIPPING TABLE
WHERE WEEK_OF_MONTH = ST.WEEK_OF_MONTH) +
(SELECT OUTGOING_AMOUNT
FROM PRODUCTION_TABLE
WHERE WEEK_OF_MONTH = ST.WEEK_OF_MONTH)
)
FROM SHIPPING_TABLE ST
WHERE ST.WEEK_OF_MONTH <= 5
为了做到这一点,您不必遍历所有行。您可以使用WEEK_OF_MONTH
的组合计算每个WEEKLY_INVENTORY
需要插入INSERT INTO SELECT
的值。
在SELECT
部分中,您可以使用其他SELECT语句为每个月的每个星期构建值,以确定Closing_Amount的值。
以上查询将是您代码中的一个简单选项,但可以通过使用JOIN
并使用以下查询来提高速度:
INSERT INTO WEEKLY_INVENTORY(Opening_Amount, Closing_Amount)
SELECT
ST.OPENING_AMOUNT
, (ST.OPENING_AMOUNT + ST.INCOMING_AMOUNT)-(ST.OUTGOING_AMOUNT + PT.OUTGOING_AMOUNT)
FROM SHIPPING_TABLE ST
INNER JOIN PRODUCTION_TABLE PT ON ST.WEEK_OF_MONTH = PT.WEEK_OF_MONTH
根据数据库架构的结构,上面的查询可能无法正常工作,因为您可能需要使用聚合函数,SUM()
我假设以及GROUPing BY产品。但是只使用你提供的伪代码,这就是对SQL的翻译。