mysql 查询根据上一行的列结果对列进行计数

yfwxisqw  于 5个月前  发布在  Mysql
关注(0)|答案(2)|浏览(58)

我有一个包含以下数据的表:

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);

字符串
你可以看到services列,我需要一个查询来选择每行计算出services的结果。services列等于前一行的services + s_registered - s_termination

我尝试使用window cte LAG()函数,但它只工作了一次。它正确地接受了第一个services列,但在下一次迭代中,LAG将该列视为null。
我想这个问题可以用递归CTE来解决,你有什么想法吗?:)

wb1gzix0

wb1gzix01#

你不需要递归cte,你可以简单地使用SUM窗口函数:

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

字符串

polhcujo

polhcujo2#

你确实可以使用递归CTE来实现这一点。例如,你可以使用它作为基础,并根据你的需要定制它:

WITH RECURSIVE cte AS (
    SELECT * FROM mytable where month = 1
    UNION ALL
    SELECT
        mytable.month,
        cte.services + cte.s_registered - cte.s_terminated,
        mytable.s_registered,
        mytable.s_terminated
    FROM cte
    INNER JOIN mytable ON cte.month + 1 = mytable.month
)
SELECT * FROM cte;

字符串

相关问题