我有两张桌子
表-A
ID PostId Item Stock Price 1 1 A 30 10 2 1 B 40 20 3 2 A 50 5 4 3 A 50 25
表-B
ID PostId Item_ID Sold Price 1 1 1 2 20 2 1 2 2 40 3 1 1 1 10 4 2 3 3 15 5 2 3 1 5
我想从上面的两个表中查询具有相同'PostID'和COUNT和SUM的一些字段组的'PostID',预期输出将是这样的
输出
ID PostId Total Item Total Stock Total Buyer(s) Total Sold Total Price 1 1 2 70 3 5 70
我试图加入它,但结果仍然错过计算
SELECT Table_A.PostId AS PostId, COUNT(Table_A.Item) AS Total_Item, SUM(Table_A.stock) AS Total_Stock, COUNT(Table_B.Item_ID) AS total_buyer, SUM( Table_B.Sold ) AS TotalSold, SUM( Table_B.Price ) AS Total_Price
FROM Table_A
LEFT JOIN Table_B
ON Table_A.PostId = Table_B.PostId
WHERE Table_A.PostId = '1'
GROUP BY Table_A.PostId
LIMIT 0 , 30
对此查询问题的任何建议?谢谢
答案 0 :(得分:0)
SELECT Table_B.PostId AS PostId,
MIN(Table_A.Total_Item) AS Total_Item,
MIN(Table_A.Total_Stock) AS Total_Stock,
COUNT(Table_B.Item_ID) AS total_buyer,
SUM( Table_B.Sold ) AS TotalSold,
SUM( Table_B.Price ) AS Total_Price
FROM Table_B
LEFT JOIN
(
SELECT PostId,
COUNT(Item) AS Total_Item,
SUM(stock) AS Total_Stock
FROM
Table_A
GROUP BY PostId
) Table_A
ON Table_B.PostId=Table_A.PostId
WHERE Table_B.PostId = '1'
GROUP BY Table_B.PostId
LIMIT 0 , 30