如何将每一行除以这些行的总和?
Posted
技术标签:
【中文标题】如何将每一行除以这些行的总和?【英文标题】:how to divide each row by the sum of those rows? 【发布时间】:2021-12-30 04:51:38 【问题描述】:我有一张表 CREDITS
包含这些列:
我应该将每一行的TOTAL_LOAN
和CREDITS_PERCENT
相乘,然后除以SUM(TOTAL_LOAN)
中的DAY_OPERATIONAL
。
我的代码不起作用。
我怎样才能做到这一点?如何正确使用 group by?
SELECT
(total_loan * credits_percent) / SUM(total_loan)
FROM
credits
WHERE
day_operational = '29.12.2021'
【问题讨论】:
你能分享样本数据集和想要的结果吗? 【参考方案1】:这就是我对问题的理解。
tc
和 tl
在这里只是为了显示用于计算最终 result
的值。
SQL> with credits (day_operational, total_loan, credits_percent) as
2 (select date '2021-12-01', 100, 1 from dual union all
3 select date '2021-12-01', 200, 4 from dual union all
4 --
5 select date '2021-12-02', 500, 5 from dual
6 )
7 select day_operational,
8 sum(total_loan * credits_percent) tc,
9 sum(total_loan) tl,
10 --
11 sum(total_loan * credits_percent) / sum(total_loan) result
12 from credits
13 group by day_operational
14 order by day_operational;
DAY_OPERAT TC TL RESULT
---------- ---------- ---------- ----------
01.12.2021 900 300 3
02.12.2021 2500 500 5
SQL>
所以:
01.12.2021: 100 * 1 + 200 * 4 = 100 + 800 = 900
100 + 200 = 300 --> 900 / 300 = 3
02.12.2021: 500 * 5 = 2500
500 = 500 --> 2500 / 500 = 5
截至day_operational
:如果它的数据类型是date
(应该是!),那么不要将它与字符串进行比较。 '29.12.2021'
是一个字符串。使用
日期文字(和我一样):date '2021-12-29'
或
to_date
具有适当格式掩码的函数:
to_date('29.12.2021', 'dd.mm.yyyy')
【讨论】:
【参考方案2】:TOTAL_LOAN * CREDITS_PERCENT / SUM(TOTAL_LOAN)
=
CREDITS_PERCENT * (TOTAL_LOAN / SUM(TOTAL_LOAN)
因此
SELECT
day_operational
, credits_percent * RATIO_TO_REPORT(total_loan) OVER (PARTITION BY day_operational)
FROM credits
见RATIO_TO_REPORT
【讨论】:
以上是关于如何将每一行除以这些行的总和?的主要内容,如果未能解决你的问题,请参考以下文章