2016-03-03 38 views
0

誰能幫我算算我查詢的一個%的份額。任何幫助表示讚賞。需要計算我的查詢的一個%分享

%股計算:這是我們需要計算%的份額。 總餘額> 500000的借款人總數,所有借款人的餘額總和除以所有借款人總額。

(
(
SELECT SUM(OUTSTANDING_BAL) 
FROM MyView 
GROUP BY BORROWER_NAME 
HAVING SUM(OUTSTANDING_BAL) > 500000 -- SUM OF BORROWER HAVING BALANCE > 500000 
) 
/-- DIVIDE BY 
(SELECT SUM(OUTSTANDING_BAL) FROM MyView) -- TOTAL SUM 
)*100 

請幫忙。

預先感謝您。

+1

您使用的是哪個數據庫? –

+0

在你的第一個'SELECT'語句中刪除'GROUP BY'並將'HAVING'改爲'WHERE'。 也嘗試'CAST [選擇語句] AS FLOAT'。除非你使用FLOATS,否則在SQL中劃分並不能很好地工作。 除此之外,請註明您正在運行到確切的問題。 –

回答

0

如果你只是想用這個信息的一個查詢,使用條件彙總:

select (sum(case when outstanding_bal > 500000 then outstanding_bal else 0 end)/
     sum(outstanding_bal) 
     ) as ratio 
from (select borrower_name, sum(outstanding_bal) as outstanding_bal 
     from MyView 
     group by borrower_name 
    ) b; 

這是假設借入可以有一個要添加了多個記錄。如果您只想考慮關於閾值的單個行,則查詢更簡單:

select (sum(case when outstanding_bal > 500000 then outstanding_bal else 0 end)/
     sum(outstanding_bal) 
     ) as ratio 
from MyView;