SQL-除其他总计外的总计百分比

时间:2018-07-17 22:45:52

标签: sql

我正在使用group bysum()提供每个州的总贷款额。 From和Where子句中发生了很多事情,但是为了概括起见,我在下面编写了伪代码,以了解我要执行的操作。除了对每个州(我正在工作的州)的贷款求和之外,我还要添加每个州相对于整个人口的百分比。问题是,我不知道如何生成分母来得出总数的百分比。

Select State, 
       Sum(LoanAmount), 

<<<How do I add the percentage of total for each state here. 
I'm not sure how to get the denominator so I can do the math.
I need to be able to sum all the  loans by basically ignoring
the group by that's in place >>>

From LoanTable
group by State

2 个答案:

答案 0 :(得分:0)

您可以使用子查询和联接。像...

WITH sumQuery AS (
 SELECT State, SUM(LoanAmount) AS Total
 FROM LoanTable 
 GROUP BY State
)
SELECT t1.state, t2.Total, (t1.LoanAmount*100)/t2.Total AS 
Percentage
FROM LoanTable t1
FULL OUTER JOIN sumQuery AS t2 ON t1.state = t2.state

以下是其工作方式的示例:SQL Fiddle

答案 1 :(得分:0)

只需使用窗口功能:

Select State,
       Sum(LoanAmount) * 1.0 / sum(sum(LoanAmount)) over () as ratio
From LoanTable
group by State;