2013-10-20 128 views
1

以下查詢返回所有擁有貸方餘額(列ID和總計)的客戶 - 是否有任何方式只返回總計?SQL(Sybase)返回計算行的總和

SELECT Customer_ID AS 'ID', 
    (
    SELECT SUM(Credit) - SUM(Debit) 
    FROM A_Sales_Ledger 
    WHERE Document_Date <= '2013-09-30' 
     AND Customer_ID = ID 
) AS 'Total' 
FROM A_Sales_Ledger 
WHERE Total > 0 
GROUP BY Customer_ID 

回答

1

嘗試是這樣的:

SELECT SUM(a.total) 
FROM (
    SELECT (SUM(Credit) - SUM(Debit)) AS "total" 
    FROM A_Sales_Ledger 
    WHERE Document_Date <= '2013-09-30' 
    GROUP BY Customer_ID 
    HAVING SUM(Credit) - SUM(Debit) > 0 
) a; 

sqlfiddle demo

+0

嘿菲利佩 - 感謝您的答覆,但只是做同樣的事情 - 返回每個客戶的所有行 - 我m試圖獲得所有返回的行的總和:-) – gchq

+0

對不起。我沒有明白,當我讀到這個問題..我更新了我的答案和小提琴 –

+0

@ gchq。小提琴是用於mysql的,因爲沒有sybase可供選擇,但我認爲它會以同樣的方式工作。 –