选择内部联接返回错误结果

时间:2019-08-16 13:33:40

标签: sql inner-join

我正在使用如下所示的选择内部联接。如何获得预期的结果?

这是sql语法:

select tgr.id, tgr.venid, sum(tgrd.qty*tgrd.pri), sum(tgrp.amo)
from tgr inner join tgrd on tgr.id = tgrd.id
inner join tgrp on tgr.id = tgrp.id
where tgr.id = 3
group by tgr.id, tgr.venid
having sum(tgrd.qty*tgrd.pri)-sum(tgrp.amo)>0;

结果:

3 | 1 | 462000 | 262000

但是我期望结果:

3 | 1 | 231000 | 131000

来自3个表的源代码:tgr,tgrd,tgrp

tgr table
id  venid
3   1

tgrd table
id  plu qty pri
3   2   2.7 45000
3   1   7.3 15000

tgrp table
id  type  amo
3   2     0
3   2     131000

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

由于从tgrtgrdtgrp之间存在多对多关系,因此您需要在JOIN插入表之前执行汇总,否则可以将每个值加倍(或更多)。该查询将为您提供所需的结果:

select tgr.id, tgr.venid, total, amo
from tgr 
inner join (select id, sum(qty*pri) as total
            from tgrd
            group by id) tgrd on tgr.id = tgrd.id
inner join (select id, sum(amo) as amo
            from tgrp
            group by id) tgrp on tgr.id = tgrp.id
where tgr.id = 3
group by tgr.id, tgr.venid
having total - amo > 0;

输出:

id  venid   total       amo
3   1       231000.00   131000

Demo on 3v4l.org