2016-08-17 69 views
-1

我有這樣的樣品數據:http://sqlfiddle.com/#!9/124b62高效的查詢來獲取賬戶餘額

什麼是獲得現金簿賬戶的開閉平衡的最佳方式(有效的查詢)?

一種方法是找到總積分並從總借方中扣除。

SELECT sum(amount) as credit_total 
FROM `cash_book` 
WHERE `type` = 'credit' 
AND `account_holder_id` =1 
AND `created_at` >= '2016-07-31 00:00:00'; 


SELECT sum(amount) as debit_total 
FROM `cash_book` 
WHERE `type` = 'debit' 
AND `account_holder_id` =1 
AND `created_at` >= '2016-07-31 00:00:00'; 

有人可以提出更好的查詢嗎?

+0

的想法SO是你嘗試,並希望查詢,當你有問題,你問你的企圖幫助。 SO不是免費的編碼或代碼轉換服務 – RiggsFolly

回答

2

單次運行總

SELECT sum(case when `type` = 'credit' then -amount else amount end) as total 
FROM `cash_book` 
WHERE AND `account_holder_id` =1 and `created_at` >= '2016-07-31 00:00:00';