We have an inventory management system which consists of an Item Catalog, Inventory, and Assets. Currently, we have an entry for every piece of inventory but we are now implementing a quantity on both the Inventory table and Assets table. For instance, data in the Inventory table looks something like this:
InventoryID | ItemID
----------------------
100 | 5
101 | 5
102 | 5
103 | 5
104 | 9
105 | 5
What we now want to do is to merge the records with the same ItemID and put the Quantity in the field:
InventoryID | ItemID | Quantity
---------------------------------
100 | 5 | 5
104 | 9 | 1
I have thousands of records that need merging and would like to know of a faster way to do this instead of the current way, which is finding the records, getting the count, deleting all but the latest record and updating the quantity field with the count (all being done manually in SSMS, not through any scripts).
Any help/suggestions would be appreciated.
Make a temp table and insert:
SELECT MIN(InventoryID), ItemID, COUNT(*) as Quantity
FROM Inventory
INTO #TEMP
GROUP BY ItemID
Then update the main table (create a quantity column first if you haven't):
UPDATE I
SET I.Quantity = T.Quantity
FROM #TEMP
WHERE I.InventoryID = T.InventoryID and I.ItemID = T.ItemID
Then delete the extra record from Inventory
DELETE
FROM INVENTORY
WHERE InventoryID not in(
SELECT InventoryID
FROM #TEMP)
Assuming you have a quantity field on your inventory table, you can update that field then delete the now-unnecessary records.
UPDATE Inventory
SET Inventory.Quantity = Computed.QCount
FROM Inventory
INNER JOIN
(
SELECT InventoryId, COUNT(*) as QCount
FROM Inventory
GROUP BY InventoryId
) as Computed
on Inventory.ItemId = Computed.ItemId
--Now Delete Duplicates
DELETE Inventory
FROM Inventory
LEFT OUTER JOIN (
SELECT MIN(InventoryId) as RowId, ItemId
FROM Inventory
GROUP BY ItemId
) as KeepRows ON
Inventory.InventoryId = KeepRows.RowId
WHERE
KeepRows.ItemId IS NULL
A simple script can create the new table that you want, then wipe out your old table and replace the data with the new.
For example, something like
SELECT
MIN(InventoryID) AS InventoryID,
ItemID,
COUNT(*) AS Quantity
INTO
NewInventoryTable
FROM
Inventory
GROUP BY
ItemID
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.