2015-06-28 87 views
0

我試圖讓每個以下款項的領域,我只得到了一個外,其他兩個返回undefined指數。MySQL的倍數SUM()一個查詢的領域內功能

我怎麼把它們作爲外場?

SELECT 
(SELECT SUM(amount) AS income 
    FROM transaction 
    WHERE 
    type = '1' && state = 'a') 

- (SELECT SUM(amount) AS expense 
    FROM transaction 
    WHERE 
    type = '2' && state = 'a') 
    AS balance 

平衡工程,但收入和費用我得到未定義的指數。

回答

1

使用條件彙總:

SELECT SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0 
      END) as income, 
     SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0 
      END) as balance 
FROM transaction; 

如果你仍然想的區別,那麼你需要重複的邏輯:

SELECT SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0 
      END) as income, 
     SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0 
      END) as expense, 
     (SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0 END) - 
     SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0 END) 
     ) as balance 
FROM transaction; 

編輯:

其實,這是最好的共同條件分解出爲WHERE條款:

SELECT SUM(CASE WHEN type = '1' THEN amount ELSE 0 END) as income, 
     SUM(CASE WHEN type = '2' THEN amount ELSE 0 END) as expense, 
     (SUM(CASE WHEN type = '1' THEN amount ELSE 0 END) - 
     SUM(CASE WHEN type = '2' THEN amount ELSE 0 END) 
     ) as balance 
FROM transaction 
WHERE state = 'a' AND type IN ('1', '2'); 

這可以在transaction(state, type, amount)採取指數的優勢。

+0

你對此很敏感,謝謝。 – Relm

1

您可以使用casesum讓每一個結果:

select sum(case when `type` = '1' then `amount` else 0 end) as `income` 
    , sum(case when `type` = '2' then `amount` else 0 end) as `expense ` 
    , sum((case when `type` = '2' then -1 else 1 end) * `amount`) as `difference` 
from `transaction` 
where `type` in ('1', '2') 
where `state` = 'a' 
+0

你爲什麼要刪除這句話哪裏你說我不應該使用「&&」,我想問爲什麼。 – Relm

+0

@Relm:因爲我想錯了 - 我猜,僅在MySQL允許這樣的語法。 – potashin

+0

噢,好的,很酷。 – Relm

1

您不能訪問incomeexpense,因爲它們只在其各自的子查詢中定義,而不在頂級查詢中定義,而頂級查詢只有一個字段 - 它們之間的差異。我把一個子查詢,然後選擇他們兩個和他們之間的差異。爲了使這個查詢更方便,刪除子查詢的需要,您可以通過在sum的參數提取不同的條件case表情模擬兩種不同where條款的行爲:

SELECT income, expense, income - expense AS balance 
FROM (SELECT SUM(CASE type WHEN 1 THEN amount ELSE NULL) AS income, 
       SUM(CASE type WHEN 2 THEN amount ELSE NULL) AS expense, 
     FROM `transaction` 
     WHERE state = 'a') t 
+0

t?什麼是「t」以及哪裏在使用? – Relm

+1

@Relm't'是一種表別名子查詢。它不是直接使用,但MySQL(和其他幾個關係數據庫)要求它擁有它。沒有它,你會得到一個錯誤,如「ERROR 1248(42000):每一個派生表必須有它自己的別名」。 – Mureinik