-2

表1

fld1 fld12 fld3 fld4

表2

fld5 fld6 fld7 

表3

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)。请帮忙。

4

2 回答 2

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功能将如何工作?

于 2013-03-12T20:56:54.627 回答
0

一些数据库引擎要求您在使用聚合时指定一个组(sum、count avg 等)

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
于 2013-03-12T20:58:00.350 回答