我有一个包含重复的ItemId
的表。我正在使用CTE
删除重复的记录,并为每个项目仅保留一个记录。我可以使用以下查询成功实现此里程碑:
Create procedure sp_SumSameItems
as
begin
with cte as (select a.Id,a.ItemId,Qty, QtyPrice,
ROW_NUMBER() OVER(PARTITION by ItemId ORDER BY Id) AS rn from tblTest a)
delete x from tblTest x Join cte On x.Id = cte.Id where cte.rn > 1
end
实际的问题是我想Sum
Qty
和QtyPrice
,然后再删除重复的记录。我应该在哪里添加Sum
函数?
问题图示:
答案 0 :(得分:3)
您不能将update
与delete
语句一起使用,而需要update
之前:
update t
set t.qty = (select sum(t1.qty) from table t1 where t1.itemid = t.itemid);
答案 1 :(得分:0)
CTE仅对一条语句有效,因此您将需要运行cte两次,一次求和然后删除,或者可以将CTE的结果放入临时表中,然后使用临时表求和,然后删除原始表中的记录。
答案 2 :(得分:0)
在第一级,删除重复记录后,您必须更新Qty和QtyPrice。
给出示例:
CREATE PROCEDURE Sp_sumsameitems
AS
BEGIN
WITH cte1
AS (SELECT a.id,
a.itemid,
Sum(qty) Qty,
Sum(qtyprice)QtyPrice,
FROM tbltest a
GROUP BY a.id)
UPDATE x
SET x.qty = c.qty,
x.qtyprice = c.qtyprice
FROM tbltest x
JOIN cte1 c
ON x.id = cte.id
WITH cte
AS (SELECT a.id,
a.itemid,
qty,
qtyprice,
Row_number()
OVER(
partition BY itemid
ORDER BY id) AS rn
FROM tbltest a)
DELETE x
FROM tbltest x
JOIN cte
ON x.id = cte.id
WHERE cte.rn > 1
END