问题描述
我的问题类似于Remove reversal pairs using SQL,但不相同。情况如下。数据(没有错别字。涉及X1的两行,并且冲销确实具有相同的REF):
SetCameraBoxImage(value)
期望的结果
ROW | REF | Amount | Comment |
1 | 00001 | 1000 | Relates to X1 |
2 | 00002 | 500 | Relates to X1 |
3 | 00003 | 100 | Relates to X2 |
4 | 00004 | 1000 | Relates to X3 |
5 | 00004 | -1000 | Reverses 00004 |
6 | 00005 | 250 | Relates to X3 |
问题:
ROW | Agg_Amt | Comment |
1 | 1500 | X1 |
2 | 100 | X2 |
3 | 250 | X3 |
以下为X3生成2行,其中1行总计为1250,而另一行为-1000
SELECT REF,SUM(Amount) FROM T1 GROUP BY REF
我尝试过的任何其他解决方案都会导致上述两个问题之一,因此共享毫无意义。
我已经使用SELECT REF,Comment,SUM(Amount) FROM T1 GROUP BY REF,Comment
解决了这个问题,但是至少可以说性能不是最佳的。
编辑
完整代码:
WHERE REF NOT IN
作为MS-Access,我无法使用临时表。
问题
是否有一个优雅的解决方案,最好没有太多的包裹和嵌套?我知道我可能在这里缺少一些简单的东西。
谢谢!
解决方法
如果我理解正确,这可能会做你想要的:
select t1.comment,sum(amount)
from t1
where not exists (select 1
from t1 as tt1
where tt1.ref = t1.ref and
tt1.amount = - t1.amount and
(t1.comment like "Reverses*" or
tt1.comment like "Reverses*"
)
)
group by t1.comment;
,
考虑双重汇总:
SELECT Replace(T1.Comment,'Relates to ','') AS [Comment],SUM(agg.SubAmount) AS Agg_Amt
FROM T1
INNER JOIN
(SELECT REF,SUM(Amount) AS SubAmount
FROM T1
GROUP BY REF) agg
ON agg.REF = T1.REF
WHERE INSTR(T1.Comment,'Reverses') = 0
GROUP BY T1.Comment