我想要得到结果:
引用= 12345
总资产= 14
总订单数= 22
当我单独运行查询时,我得到了正确的结果,但是当我将两个查询放在一起时,我的结果是关闭的(这是因为表b和c不代表彼此)
我的表摘要如下:
Select a.Quote, SUM(b.Quantity) As 'Total Assets'
FROM a
INNER JOIN b ON b.aId = a.Id
GROUP By a.Quote
结果:12345:14
Select a.Quote, SUM(c.Quantity) As 'Total Ordered'
FROM a
INNER JOIN c on c.aId = a.Id
GROUP By a.Quote
结果:12345:22
然而,当我把它们放在一起时:
Select a.Quote, SUM(b.Quantity)As 'Total Assets',SUM(c.Quantity) As 'Total Ordered'
FROM a
INNER JOIN b on b.Aid = a.Id
INNER JOIN c on c.Aid = a.Id
GROUP BY a.Quote
结果12345:56:308
我和小组一起玩了但是从来没能得到正确的结果。有什么想法吗?
到目前为止,我提出的解决方案是
With abc AS
(
Select a.Quote, SUM(b.Quantity) As 'Total Assets'
FROM a
INNER JOIN b ON b.aId = a.Id
GROUP By a.Quote
)
SELECT abc.* , SUM(c.Quantity) As ' Total Ordered'
FROM abc
INNER JOIN c ON c.aid = a.Id
GROUP BY (all in abc)
这似乎不是获得结果的最佳方式..
答案 0 :(得分:1)
也许使用Left JOIN。 INNER JOIN将重复b和c行。另外,请尝试查看以下结果:
Select a.Quote, b.Quantity As 'Total Assets', c.Quantity As 'Total Ordered'
FROM a
INNER JOIN b on b.Aid = b.Id
INNER JOIN c on c.Aid = c.Id
GROUP BY a.Quote
并检查它是否是正确的计算结果。然后将其与:
进行比较Select a.Quote, b.Quantity As 'Total Assets', c.Quantity As 'Total Ordered'
FROM a
LEFT JOIN b on b.Aid = b.Id
LEFT JOIN c on c.Aid = c.Id
GROUP BY a.Quote