月至月增长(同一列)

时间:2019-01-06 03:14:22

标签: mysql sql

我已经查看了其他解决方案,但似乎没有一个对我有用。我有一个非常简单的问题。

我有一个名为止赎的表。它具有3列,分别为:foreclosures_id,period和丧失抵押品赎回权。句点是唯一的主键。止赎列的数据类型为十进制。

我当前的查询是:     选择     MONTHNAME(时段)为AS Reported_Month,     YEAR(期间)AS Reported_Year,     FORMAT(foreclosures,0)AS止赎,

(SELECT FORMAT(SUM(f2.foreclosures),0) FROM foreclosures f2
WHERE f2.period <= f1.period AND f1.foreclosures IS NOT NULL)  
AS YTD_Total,

MONTHNAME(DATE_SUB(period, INTERVAL 2 MONTH))  AS Real_Month,
YEAR(DATE_SUB(period, INTERVAL 2 MONTH))  AS Real_Year

FROM foreclosures f1;

我正在尝试生成以下“增长”列。请帮忙吗?

    +----------------+---------------+--------------+------------+
    | Reported_Month | Reported_Year | Foreclosures | Growth %  |
    +----------------+---------------+--------------+------------+
    | January        |          2016 |          201 |            |
    | February       |          2016 |          332 | 65.2%      |
    | March          |          2016 |          240 | -27.7%     |
    | April          |          2016 |          369 | 53.8%      |
    +----------------+---------------+--------------+------------+

1 个答案:

答案 0 :(得分:2)

您可以使用与累积总和类似的逻辑来获取上一时期的止赎房屋:

SELECT MONTHNAME(period) AS Reported_Month,
       YEAR(period) AS Reported_Year,
       FORMAT(foreclosures, 0) AS Foreclosures,
       (SELECT f2.foreclosures
        FROM foreclosures AS f2
        WHERE f2.period < f.period AND
              f.foreclosures IS NOT NULL
        ORDER BY f2.period DESC
       ) as prev_foreclosures
FROM foreclosures f;

对于增长测度,只需应用将用于该计算的算法即可。