如何计算每年总数的百分比

时间:2018-08-24 18:45:22

标签: sql sql-server tsql

在SQL Server中,我有一个查询

SELECT
    fundingyear, tran_type, 
    COUNT(tran_type) AS total_tran
FROM
    vw_LoanRpt
GROUP by 
    fundingyear, tran_type
ORDER BY 
    FundingYear

它返回以下结果:

  fundingyear tran_type   total_tran
1 2017        Purchase    2501
2 2017        Refianance  3444
3 2018        Purchase    2666
4 2018        Refianance  4787

我想做的是添加一列来计算每年total_tran的百分比。这样一来,2017年的total_tran的总和就分解了百分比,而2018年的百分率则保持不变。非常感谢您能帮助我走上正确的道路。

2 个答案:

答案 0 :(得分:2)

由于我没有数据,所以我无法对其进行测试,但这应该可以工作(我想您希望每年将total_tran的{​​{1}}的边际贡献归因于tran_type):

    SELECT fundingyear, tran_type, total_tran, 
           (100*total_tran)/SUM(total_tran) OVER(PARTITION BY funding_year) AS total_tran_perc
    FROM
    (
    SELECT fundingyear, tran_type, COUNT(tran_type) AS total_tran
    FROM vw_LoanRpt
    GROUP by fundingyear, tran_type
    ) a1
    ORDER BY fundingyear

答案 1 :(得分:0)

您可以在没有子查询的情况下执行此操作:

SELECT fundingyear, tran_type, 
       COUNT(*) AS total_tran,
       COUNT(*) * 1.0 / SUM(COUNT(*)) OVER (PARTITION BY fundingyear) as year_ratio
FROM vw_LoanRpt
GROUP by fundingyear, tran_type
ORDER BY FundingYear;