我希望能够从两个SELECT查询中获取我在SUM()中生成的两个值,并减去这些值以获得结果(OutstandingFunds)。
这是我的两个SELECT查询:
声明(1):
SELECT SUM(Cf.Amount) AS ClearedFunds
FROM (
SELECT Amount FROM PAYMENT1 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT2 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT3 WHERE `Status` = "Cleared") AS Cf;
声明(2):
SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = “Sold”;
感谢您的时间
答案 0 :(得分:5)
如果您不需要显示总销售额和清算资金的单独小计,您可以这样做:
SELECT SUM(Total.`Price`) AS ClearedFunds
FROM (
SELECT `Price` FROM PROPERTY WHERE `Status` = 'Sold'
UNION ALL
SELECT (`Amount` * -1) AS `Price` FROM PAYMENT1 WHERE `Status` = 'Cleared'
UNION ALL
SELECT (`Amount` * -1) AS `Price` FROM PAYMENT2 WHERE `Status` = 'Cleared'
UNION ALL
SELECT (`Amount` * -1) AS `Price` FROM PAYMENT3 WHERE `Status` = 'Cleared'
) AS Total;
我假设你想在这里从总销售额中扣除已清算的资金。
答案 1 :(得分:1)
你几乎就在那里......这是工作SQL
:
SELECT (SELECT SUM(Cf.Amount) AS ClearedFunds
FROM (
SELECT Amount FROM PAYMENT1 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT2 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT3 WHERE `Status` = "Cleared") as Cf)
- (SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = "Sold") as Result;
这是SQL小提琴,以便您可以使用测试数据:http://sqlfiddle.com/#!2/18677/11
答案 2 :(得分:0)
在您的情况下,您可以使用SELECT ... INTO ...
:
SELECT SUM(Cf.Amount) AS ClearedFunds
FROM (
SELECT Amount FROM PAYMENT1 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT2 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT3 WHERE `Status` = "Cleared") INTO @cf;
SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = “Sold” INTO @ts;
然后你可以在任何其他查询中减去或使用它们,如下所示:
SELECT @ts - @cf;
答案 3 :(得分:0)
你在找这个吗?
SELECT C.ClearedFunds - P.TotalSales
FROM (
SELECT SUM(Cf.Amount) AS ClearedFunds
FROM (
SELECT Amount FROM PAYMENT1 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT2 WHERE `Status` = "Cleared"
UNION ALL
SELECT Amount FROM PAYMENT3 WHERE `Status` = "Cleared") AS Cf) C,
(SELECT SUM(Price) AS TotalSales
FROM PROPERTY
WHERE Status = “Sold”) P
;