Skip to content
Advertisement

SQL Server query duplicating rows based on inventory locations that have been claused out

My current code is duplicating results per item_id. I am summing the previous three months usage per item in two locations. I do have more locations but I limited it in the WHERE clause. I think the query is showing the extra results due to the other locations. Can someone help me clean up my code?

The usage column is YYYYMM format

Table for Inventory Quantity on Hand:

Table for Inventory Usage:

My desired result sums the usage for the previous three months per location and show the current quantity in inventory.

Advertisement

Answer

One option uses a correlated subquery:

The conditions on the date may look lengthy, however they look to me like the most efficient way to filter; they make the query SARGeable, and would take advantage of an index on inventory_usage(location, inv_id, year_period).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement