2013-06-27 57 views
2

我想加入這兩個查詢,我想從PQuantity中減去SQuantity,從PAmount中減去SAmount。我如何通過一個查詢來實現這一點。在具有聚合函數的Select查詢中加入多個表

SELECT   
SUM(QtyShare) AS SQuantity, SUM(QtyShare * Rate) AS SAmount,CompanyId 
FROM Sales 
WHERE (UserId = 1) 
GROUP BY CompanyId 

SELECT SUM(Quantity) AS PQuantity, SUM(Quantity * Rate) AS PAmount,CompanyId 
FROM (SELECT UserId, CompanyId, Quantity, Rate AS Rate 
     FROM Purchase 
     UNION ALL 
     SELECT UserId, CompanyId, Quantity, 0 AS Rate 
     FROM Bonus 
     UNION ALL 
     SELECT UserId, CompanyId, Quantity, Rate AS Rate 
     FROM RightShare) AS t 
WHERE (UserId = 1) GROUP BY CompanyId 
+0

是否銷售表有(列數或組合,製成獨特的記錄)一列,它是在任何購買,紅利或RightShare可用於加入? – ChrisProsser

+0

CompanyId,第二個查詢返回每個公司基礎上的一些結果,我想從每個公司基礎上的銷售表中減去,例如:WHERE Sales.CompanyId = Purchase.CompanyId – user2516394

回答

3

嘗試:

SELECT CompanyId, 
     SUM(PQuantity) PQuantity, 
     SUM(PQuantity * PRate) PAmount, 
     SUM(SQuantity) SQuantity, 
     SUM(SQuantity * sRate) SAmount 
     SUM(PQuantity) - SUM(SQuantity) TQuantity, 
     SUM(PQuantity * PRate) - SUM(SQuantity * sRate) TAmount 
FROM 
(SELECT UserId, CompanyId, Quantity PQuantity, Rate PRate, 0 SQuantity, 0 SRate 
FROM Purchase 
UNION ALL 
SELECT UserId, CompanyId, Quantity PQuantity, 0 PRate, 0 SQuantity, 0 SRate 
FROM Bonus 
UNION ALL 
SELECT UserId, CompanyId, Quantity PQuantity, Rate PRate, 0 SQuantity, 0 SRate 
FROM RightShare 
UNION ALL 
SELECT UserId, CompanyId, 0 PQuantity, 0 PRate, QtyShare SQuantity, Rate SRate 
FROM Sales) sq 
WHERE (UserId = 1) 
GROUP BY CompanyId