我有以下sql语句:
select
a.desc
,sum(bdd.amount)
from t_main c
left outer join t_direct bds on (bds.repid=c.id)
left outer join tm_defination def a on (a.id =bds.sId)
where c.repId=1000000134
group by a.desc;
当我运行它时,我得到以下结果:
desc amount
NW 12.00
SW 10
当我尝试添加另一个左外连接以获得另一组值时:
select
a.desc
,sum(bdd.amount)
,sum(i.amt)
from t_main c
left outer join t_direct bds on (bds.repid=c.id)
left outer join tm_defination def a on (a.id =bdd.sId)
left outer join t_ind i on (i.id=c.id)
where c.repId=1000000134
group by a.desc;
它基本上使金额字段加倍,例如:
desc amount amt
NW 24.00 234.00
SE 20.00 234.00
结果应该是:
desc amount amt
NW 12.00 234.00
SE 10.00 NULL
如何解决这个问题?
最佳答案
如果您确实需要接收您提到的数据,您可以使用子查询来执行所需的计算。在这种情况下,您的代码可能如下所示:
select x.[desc], x.amount, y.amt
from
(
select
c.[desc]
, sum (bdd.amount) as amount
, c.id
from t_main c
left outer join t_direct bds on (bds.repid=c.id)
left outer join tm_defination_def bdd on (bdd.id = bds.sId)
where c.repId=1000000134
group by c.id, c.[desc]
) x
left join
(
select t.id, sum (t.amt) as amt
from t_ind t
inner join t_main c
on t.id = c.id
where c.repID = 1000000134
group by t.id
) y
on x.id = y.id
在第一个子选择中,您将收到前两列的聚合数据:desc
和 amount
,根据您的需要进行分组。
第二个选择将为第一组的每个 id
返回所需的 amt
值。
这些结果之间的左连接将给出所需的结果。由于性能问题,将 t_main
表添加到第二个选择中。
另一种解决方案如下:
select
c.[desc]
, sum (bdd.amount) as amount
, amt = (select sum (amt) from t_ind where id = c.id)
from #t_main c
left outer join t_direct bds on (bds.repid=c.id)
left outer join tm_defination_def bdd on (bdd.id = bds.sId)
where c.repId = 1000000134
group by c.id, c.[desc]
结果是一样的。基本上,amt 总和的计算不是使用嵌套选择,而是对结果连接的每一行执行内联。如果表很大,第二个解决方案的性能会比第一个解决方案更差。
关于sql - 多个表的左外连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19627738/