我做了很多搜索,然后尝试自己写。我想写一个SQL查询来计算重复条目的数量,然后将重复条目的数量添加到第一个可用条目的数量中。这是我正在开发的游戏。
第一个条目是要显示的第一个CustomerID,ItemID,Var1。因为我们需要按这3个字段对所有内容进行排序。
重复条目是ItemID和Var1相同的地方,然后我们要添加以将重复记录的数量添加到第一条记录中。库存ID无关紧要,因为这是主键。我们无法添加具有不同客户ID的记录
列是
CREATE TABLE [dbo].[UsersInventory]
( [InventoryID] bigint NOT NULL IDENTITY(1,1),
[CustomerID] int NOT NULL ,
[CharID] int NOT NULL DEFAULT ((0)) ,
[BackpackSlot] int NOT NULL DEFAULT ((0)),
[ItemID] int NOT NULL,
[LeasedUntil] datetime NOT NULL,
[Quantity] int NOT NULL DEFAULT ((1)),
[Var1] int NOT NULL DEFAULT ((-1)),
[Var2] int NOT NULL DEFAULT ((-1)),
[Durability] int NULL )
从问题的描述来看,您似乎需要类似下面的代码。
本质上,您首先需要计算所有唯一项目的总和,然后删除所有重复项,最后更新剩余项目的数量
-- Temporary table to hold the sums
declare @tempSum table
( CustomerID int,
ItemID int,
Var1 int,
InventoryID int,
Quantity int )
-- Get the sum of quantity per Customer, Item and Var1
-- This also get the first InvetoryID, assuming that the smallest number is the first one
insert @tempSum
( CustomerID,
ItemID,
Var1,
InventoryID,
Quantity )
select CustomerID,
ItemID,
Var1,
min(InventoryID),
sum(Quantity)
from UsersInventory
group by CustomerID,
ItemID,
Var1
begin transaction
-- Remove duplicate items
delete usi
from UsersInventory usi
join
@tempSum tmp on tmp.CustomerID = usi.CustomerID
and tmp.ItemID = usi.ItemID
and tmp.Var1 = usi.Var1
and tmp.InventoryID <> usi.InventoryID -- This ensures all items get deleted that are didn't mark as our firsts
-- Update the quantity that we summed earlier
update usi
set Quantity = tmp.Quantity
from UsersInventory usi
join
@tempSum tmp on tmp.CustomerID = usi.CustomerID
and tmp.ItemID = usi.ItemID
and tmp.Var1 = usi.Var1
and tmp.InventoryID = usi.InventoryID
commit transaction
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句