I have a table with this data: enter image description here

create table my_table (
    month varchar(2),
    services integer null,
    s_registered integer,
    s_terminated integer
);

insert into my_table(month, services, s_registered, s_terminated) values
    ('01', 395, 14, 14),
    ('02', null, 5, 9),
    ('03', null, 19, 15),
    ('04', null, 30, 11),
    ('05', null, 13, 15),
    ('06', null, 8, 11),
    ('07', null, 10, 17),
    ('08', null, 13, 17),
    ('09', null, 5, 10),
    ('10', null, 10, 19),
    ('11', null, 7, 22),
    ('12', null, 18, 13);

You can see the services column and I need a query to select the result with the calculated services in each row. The services column is equal to services + s_registered - s_termination of the previous row.enter image description here

我try 使用Window CTE Lag()函数,但它只起作用一次.它正确地接受了第一个services列,但在下一次迭代中,LAG将该列视为NULL.

我觉得这个问题可以用递归CTE来解决,你有什么 idea 吗?:)

推荐答案

您不想为此使用递归CTE,只需使用SUM窗口函数:

select
    month,
    sum(coalesce(services,0) + s_registered - s_terminated) over (order by month) services,
    s_registered,
    s_terminated
from my_table
order by month;

Mysql相关问答推荐

一次又一次地删除事件行

S在我的SQL代码中的外键出了什么问题?

如何在WooCommerce中更新pm_Virtual.meta_Value=#39;否

在MySQL中查找包含无效正则表达式的行

Mysql根据文本语言或行数将列拆分为多列

使用 autocommit = 0 和 InnoDB 表的 LOCK TABLES 检测死锁

关联同一个表中的两列

为什么order by子句可以利用索引?

检索按键列值分组的最新日期 (MySql)

MySql部分匹配基于部分查询代码

从多到多表中 Select 数据而无需重复

此插页中的X是什么> X'3C2F756C3E'

Sequelize Query 查找日期范围内的所有记录

在 PHP/MySQL 中将日期时间存储为 UTC

MySQL 连接运算符

如何在 MySQL 中删除此索引?

比较 MySQL 中的日期忽略 DateTime 字段的时间部分

设计用户角色和权限系统的最佳实践?

获取最后一组不同的记录

SELECT INTO 和未声明的变量错误