我需要一些帮助。
我希望在任何账单中完全具有相同ID的材料数量。
像这样bill no. 001
jellopy x1ea
jellopy x1ea
jellopy x1ea
zargon x1ea
结果应该是
bill no. 001
jellopy x3ea
zargon x1ea
所以,我想做这样的事情
1.select + sum 2.update 3.delete duplicate
这是我的旧(dbill)表
dbill
id mat qty
01 A1 1
01 A1 1
01 A1 1
01 A2 1
id mat qty
[01 A1 1] < same mat&id = SUM it
[01 A1 1] < same mat&id = SUM it
[01 A1 1] < same mat&id = SUM it
01 A2 1
这是SQLFiddle for test http://sqlfiddle.com/#!15/b30a3c
1使用相同材料的SUM数量
SELECT mat,id,sum(qty) result
FROM dbill
GROUP BY id,mat
[2]得到了这样的结果
id mat qty
01 A1 3
01 A2 1
[3]所以......我会像这样更新
UPDATE dbill
SET qty = result
FROM dbill t
INNER JOIN
(SELECT mat,id,sum(qty) result
FROM dbill
GROUP BY id,mat) s
ON s.id = t.id
AND s.mat = t.mat
问题是当我[3] UPDATE这里是结果
id mat qty
01 A1 3
01 A1 3
01 A1 3
01 A2 3
因为正确的结果应该是
id mat qty
01 A1 3
01 A1 3
01 A1 3
01 A2 1 <
非常感谢您的理解和回答......
答案 0 :(得分:1)
对我来说,您的查询似乎没问题,只需将UPDATE dbill
替换为UPDATE t
UPDATE t <----
SET qty = result
FROM dbill t
INNER JOIN
(SELECT mat,id,sum(qty) result
FROM dbill
GROUP BY id,mat) s
ON s.id = t.id
AND s.mat = t.mat
答案 1 :(得分:0)
这可能不太优雅但应该有效
UPDATE dbill t
SET t.qty = (select sum(qty) from dbill t2 where t2.id=t.id and t2.mat=t.mat)
答案 2 :(得分:0)
问题解决了!!!
在这里,这是我的解决方案。 (我可以从我的应用程序获得t3.id,所以我只是连接它。)
UPDATE dbill t3
SET qty = t2.result
FROM (
SELECT matno,hbill_ids,sum(qty) result
FROM dbill t1
GROUP BY hbill_ids,matno) t2
WHERE ( t3.hbill_ids = t2.hbill_ids
AND t3.matno = t2.matno )
AND ( t3.id = 372
OR t3.id = 373
OR t3.id = 374
OR t3.id = 375 );
DELETE FROM dbill t3
WHERE id IN ( SELECT id
FROM dbill y1
WHERE EXISTS (
SELECT *
FROM dbill y2
WHERE y1.matno = y2.matno
AND y1.qty = y2.qty
AND y1.hbill_ids = y2.hbill_ids
AND y1.id < y2.id
AND ( t3.id = 372
OR t3.id = 373
OR t3.id = 374
OR t3.id = 375 )
));