2

我想加入这两个查询,我想从 PQuantity 中减去 SQuantity,从 PAmount 中减去 SAmount。我怎样才能通过一个查询来实现这一点。

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
4

1 回答 1

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
于 2013-06-27T10:57:41.873 回答