gpt4 book ai didi

mysql - SQL 查询 - 按月到期的数据透视贷款摘要

转载 作者:行者123 更新时间:2023-11-28 23:37:42 25 4
gpt4 key购买 nike

这看起来很简单,但我正在用头撞墙来弄明白。

我有一张贷款数据表,我想对每个月的到期付款进行透视和汇总。这类似于“静态池分析”,其中每个贷款池为行,月份为列。您可以使用此 SQL Fiddle 查看示例数据.

我创建了一个 90 second screencast如果有帮助,可以更好地解释我需要的数据透视和摘要结果。感谢您的帮助!

最佳答案

如果它不需要是动态的,在 SUM 中使用 CASE WHEN 或 IF 语句应该起到 MySQL 中的 PIVOT 的作用:

SELECT 
PoolMonth,
SUM(OriginationAmt) AS Origination,
SUM(IF(PmtDue = 201512, AmtPaid, 0)) AS `201512`,
SUM(IF(PmtDue BETWEEN 201512 AND 201601, AmtPaid, 0)) AS `201601`,
SUM(IF(PmtDue BETWEEN 201512 AND 201602, AmtPaid, 0)) AS `201602`
FROM
Loans
GROUP BY
PoolMonth;

http://sqlfiddle.com/#!9/47701/16

获取总的 OriginationAmt、PoolMonth/PmtDue 的运行总计有点冗长,并且只输出最新的运行总计,没有硬编码任何东西,但我们开始吧:-)

SELECT
t.PoolMonth,
t.TtlOriginationAmt,
t.PmtDue,
t.RtAmtPaid
FROM
(
SELECT
l.PoolMonth,
l.OriginationAmt,
orig.TtlOriginationAmt,
l.PmtDue,
/* Row_Number() equivalent for MySQL http://blog.sqlauthority.com/2014/03/09/mysql-reset-row-number-for-each-group-partition-by-row-number/ */
/* Assign a Row Number for each Payment Due month for the individual Pool month in ascending order (ORDER BY clause important in this subquery) */
@RowNumber := CASE WHEN @PoolMonth = l.PoolMonth AND @PmtDue = l.PmtDue THEN @RowNumber + 1 ELSE 1 END AS PoolPmtRowNumber,
/* Use the total count of PmtDue month rows for each PoolMonth so we can limit our results to the final row */
lr.PoolPmtLastRow,
l.AmtPaid,
/* Running total of Amount Paid for the individual Pool month in order of Payment Due month (ORDER BY clause important in this subquery) */
@RtAmtPaid := CASE WHEN @PoolMonth = l.PoolMonth THEN @RtAmtPaid + l.AmtPaid ELSE l.AmtPaid END AS RtAmtPaid,
/* Keep track of the Pool month we're totalling */
@PoolMonth := l.PoolMonth,
/* Keep track of the Payment Due month we're ordering */
@PmtDue := l.PmtDue
FROM
Loans l
JOIN
/* Get the Total Origination Amount */
(SELECT PoolMonth, SUM(OriginationAmt) AS TtlOriginationAmt FROM Loans GROUP BY PoolMonth) orig ON orig.PoolMonth = l.PoolMonth
JOIN
/* Get the total number of records by Pool/Payment due month so we can filter to the last row */
(SELECT PoolMonth, PmtDue, COUNT(1) AS PoolPmtLastRow FROM Loans GROUP BY PoolMonth, PmtDue) AS lr ON lr.PoolMonth = l.PoolMonth AND lr.PmtDue = l.PmtDue
CROSS JOIN
/* Reset the variables we need for tracking */
(SELECT @RtAmtPaid:=0,@PoolMonth:=0,@PmtDue:=0,@RowNumber:=0) var
/* Order by Pool/Payment Due month */
ORDER BY
l.PoolMonth,
l.PmtDue
)t
WHERE
/* Filter to the last row */
t.PoolPmtRowNumber = t.PoolPmtLastRow;

http://sqlfiddle.com/#!9/47701/45

从那里开始,在 Excel 或其他任何地方转换结果应该非常容易。

关于mysql - SQL 查询 - 按月到期的数据透视贷款摘要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35327580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com