简体   繁体   English

删除记录并更新数量

[英]Delete records and update quantity

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: 现在,我们要做的是合并具有相同ItemID的记录,并将“数量”放入字段中:

 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). 我有成千上万条需要合并的记录,并且想知道一种更快的方法来代替当前的方法,即找到记录,获取计数,删除除最新记录以外的所有记录以及用计数更新数量字段(所有操作均在SSMS中手动完成,而不是通过任何脚本完成)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM