我做了很多搜索,并试图自己写。我想写一个SQL查询来计算重复条目的数量,然后将重复条目的数量添加到可用的第一个条目的数量。这是我正在努力的游戏。
第一个条目是要显示的第一个CustomerID,ItemID,Var1。因为我们需要对这3个字段进行排序。
重复条目是ItemID和Var1相同的地方,然后我们要添加将重复记录的数量添加到第一条记录。库存ID对此不以为然,因为它是主键。我们无法添加具有不同CustomerID
的记录列是
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 )
答案 0 :(得分:0)
试试这个:
create table T1 as (
select t1.*,count(*)-1 as records_quantity from T t1 group by t1.CustomerID,t1.ItemID,t1.Var1);
delete from T;
insert into T (select * from T1);
答案 1 :(得分:0)
根据您对问题的描述,听起来您需要类似下面代码的内容。
实质上,您需要先计算所有唯一项目的总和,然后删除所有重复项,最后更新剩余项目的数量
-- 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