如何使用连接从两个不同的表中检索两个聚合列?

How to retrieve two aggregate columns from two different tables using joins?

我想从 ITEMS TABLE 中检索 Price Column 的总和并将其与 GOODS TABLE 相结合。问题是当我尝试连接这些表时,Goods Table 中数量列 gQnty 的总和给出 84 而不是 DISH A14。任何人都可以帮助我如何完成这项任务,我可以通过相同的查询获得确切的数量 gQnty 和价格 iPrice

TABLE 商品

gID | gName | gQnty
-------------------------
1     DISH A   10
2     DISH B   12
3     DISH A   4

TABLE 项:

iID | gID | iItem | iPrice
--------------------------
1      1    Sugar    200
2      1    Milk     300
3      1    Fruits   100

4      2    Oil      200

5      3    Sugar    100
6      3    Milk     50
7      3    Fruits   40

我的查询:

select g.gName, sum(g.gQnty)[gQnty], sum(i.iPrice)[iPrice]
from goods g join items i
on g.gID = i.gID
group by g.gName

预期结果:

gName  | gQnty | iPrice
----------------------------
DISH A |  14   |  790  
DISH B |  12   |  100

LEFT JOIN 是个好主意

WITH A AS (
SELECT gName, SUM(ITEMS.iPrice) AS iPrice
FROM GOODS
LEFT JOIN ITEMS
ON GOODS.gID = ITEMS.gID
GROUP BY gName 
)
SELECT gName, 
(SELECT SUM(gQnty) FROM GOODS WHERE GOODS.gName = A.gName GROUP BY gName ) AS gQnty,
iPrice
FROM A

dbfiddle

试试这个

select g.gName, max(g.gQnty)[gQnty], sum(i.iPrice)[iPrice]
from goods g join items i
on g.gID = i.gID
group by g.gName

甚至

select g.gName, avg(g.gQnty)[gQnty], sum(i.iPrice)[iPrice]
from goods g join items i
on g.gID = i.gID
group by g.gName