sql - 使用从最后一个值到下一个填充值的值更新列

标签 sql mysql

我有一个表格,其中包含每月金额和上个月的金额。

每个月我都需要携带上个月的金额(如果不存在)。

为了更好地解释(并举例),我可能有以下数据;

Month,Amount,Previous
2019-01-01,100,0
2019-02-01,100,100
2019-03-01,100,null
2019-04-01,100,null
2019-05-01,100,200
2019-06-01,100,null

所以我想将 100 带到三月和四月,然后将 200 带到六月,所以它看起来像这样;

Month,Amount,Previous
2019-01-01,100,0
2019-02-01,100,100
2019-03-01,100,100
2019-04-01,100,100
2019-05-01,100,200
2019-06-01,100,200

我只是空白,我知道有一种方法,但头脑根本无法将其组合在一起。

我认为这将涉及同一个表上的 LEFT JOIN 并获取 MIN 月份值,其中日期的金额大于上个月值但不大于下个月值。

或者它将在 WHERE 子句和 LEFT JOIN 中执行子查询。

到目前为止,我已经管理了以下内容,但它为每个先前值(100 和 200)重复了 5 月和 6 月行。

SELECT
    *
FROM
    table1 t1
    LEFT JOIN
        table1 t2 ON
            t1.month > t2.month
Month,Amount,Previous
2019-01-01,100,0
2019-02-01,100,100
2019-03-01,100,100
2019-04-01,100,100
2019-05-01,100,200
2019-05-01,100,100
2019-06-01,100,200
2019-06-01,100,100

最佳答案

drop table if exists t;
create table t
(Month date,Amount int,Previous int);
insert into t values
('2019-01-01',100,0),
('2019-02-01',100,100),
('2019-03-01',100,null),
('2019-04-01',100,null),
('2019-05-01',100,200),
('2019-06-01',100,null);

select t.*,
        case when previous is null then
            (select previous from t t1 where t1.month < t.month and t1.previous is not null order by month desc limit 1)
        else previous
        end as previousdownfilled
from t;

+------------+--------+----------+--------------------+
| Month      | Amount | Previous | previousdownfilled |
+------------+--------+----------+--------------------+
| 2019-01-01 |    100 |        0 |                  0 |
| 2019-02-01 |    100 |      100 |                100 |
| 2019-03-01 |    100 |     NULL |                100 |
| 2019-04-01 |    100 |     NULL |                100 |
| 2019-05-01 |    100 |      200 |                200 |
| 2019-06-01 |    100 |     NULL |                200 |
+------------+--------+----------+--------------------+
6 rows in set (0.00 sec)

其中 case 语句检查是否需要完成某些操作,并且相关的 cub 查询会执行此操作。但我怀疑这项工作应该在创建此表的代码中完成。

关于sql - 使用从最后一个值到下一个填充值的值更新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56788469/

相关文章:

sql - PostgreSQL 中数字之间的异或

PHP-MySQL 删除记录

sql - MS SQL Server 使用复合键选择多行

php - 在 XAMPP 中创建 php Web 服务器

mysql - 从一种方法调用另一种方法

sql - Azure Synapse SQL 按需分页(OFFSET/FETCH)

sql - 我如何在每个组中只选择最小创建日期的 ID

mysql - mysql 中的 NULL 拒绝

mysql - SQL 查询 - 在日期和时间之间查找

mysql - 如何有效地对基于时间的数据集进行分组以计算组平均值和中位数