表A和表B之间有一对多,表B和表C之间也有一对多。我需要列出表B中的所有记录,以及表A中的父表和a的总和()。 C中的特殊字段。我该怎么做?
我认为它类似于:
SELECT A.fldlist,
B.fldlist,
SUM(C.field)
FROM A
INNER JOIN B ON A.key = b.FK
LEFT OUTER JOIN C on B.key = C.FK
GROUP BY B.field
有什么想法吗?非常感谢...
答案 0 :(得分:5)
关闭,但您需要按SELECT中的所有非聚合列进行分组。
SELECT A.fldlist,
B.fldlist,
SUM(C.field)
FROM A
INNER JOIN B ON A.key = b.FK
LEFT OUTER JOIN C on B.key = C.FK
GROUP BY A.fldlist, B.fldlist
答案 1 :(得分:1)
如果您想按A和B中的所有字段进行分组,则可以随时执行此操作
With tmp as
(
SELECT c.FK, SUM(C.field) as field
FROM C
GROUP BY c.FK
)
SELECT A.*, B.*, tmp.FK, tmp.field
FROM A
INNER JOIN B ON A.key = b.FK
LEFT OUTER JOIN tmp ON b.key = tmp.FK