2013-02-13 136 views
3

我希望能夠從兩個SELECT查詢中獲取在SUM()中生成的兩個值,並減去這些值以獲得結果( OutstandingFunds)。MySQL - 希望減去兩個SELECT語句中的兩個SUM()值

這是我的兩個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」; 

謝謝您的時間

回答

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; 

我假設你是想從這裏銷售總額減去清算資金。

+0

感謝。它非常完美! :) – Steve 2013-02-13 01:57:48

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; 
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 
; 
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