SQL:3个表,包含2个表中的选择列和一列上的总和

时间:2013-03-12 20:53:55

标签: sql

TBL1

fld1 fld12 fld3 fld4

Tbl2

fld5 fld6 fld7 

TBL3

fld8 fld9 fld10 fld11 fld12 fld13

查询:

select fld8, fld11, fld12, sum(fld3), fld4
from tbl1, tbl2, tbl3
where fld1=fld5 and fld2=fld6 and fld7=fld8

查询未运行。我使用了连接,但总和不起作用。使用fld3的查询可以有效但sum(fld3)无效。请帮忙。

2 个答案:

答案 0 :(得分:0)

您必须拥有group by

select fld8, fld11, fld12, sum(fld3), fld4 
from tbl1, tbl2, tbl3 where fld1=fld5 and fld2=fld6 and fld7=fld8 
group by fld8, fld11, fld12, fld4

否则sum功能如何运作?

答案 1 :(得分:0)

某些数据库引擎要求您在使用聚合(sum,count avg etc)

时指定一个组
select fld8, fld11, fld12, sum(fld3), fld4
from tbl1, tbl2, tbl3
where fld1=fld5 and fld2=fld6 and fld7=fld8
GROUP BY fld8, fld11, fld12, fld4

或以不同的方式写作

select fld8, fld11, fld12, sum(coalesce(fld3,0)), fld4
from tbl1 
INNER JOIN tbl2 on fld1=fld5 and fld2=fld6
INNER JOIN tbl3 on  fld7=fld8
GROUP BY fld8, fld11, fld12, fld4

现在假设你在所有3个表中都有记录。如果不是这种情况,您可能需要使用外连接,并根据引擎在sum字段或nvl上合并。

所以也许......

SELECT fld8, fld11, fld12, sum(coalesce(fld3,0)), fld4
FROM  tbl1 
LEFT JOIN tbl2 on fld1=fld5 and fld2=fld6
LEFT JOIN tbl3 on  fld7=fld8
GROUP BY fld8, fld11, fld12, fld4