MySQL 使用 LAG() 函数时忽略 NULL 值

MySQL ignore NULL Value while using LAG() function

我想计算全年发生的每月付款差异。例如,如果我在 2 月份有 100 笔付款,而在 3 月份有 120 笔付款,则差值为 20。我已经使用 LAG() 进行了查询,但我面临的唯一问题是查询正在显示空值。由于 2 月之前没有付款,MonthByMonth 将显示 NULL,我想跳过那一行。 下面是样本数据集

这是我正在使用的查询

SELECT date_format(payment_date,'%M') 'Month', COUNT(*) - LAG(COUNT(*)) 
OVER (ORDER BY FIELD(date_format(payment_date,'%M'),
'January','February','March','April','May','June','July','August','September','October','November','December')) 
AS 'MonthByMonthChange'
from main
GROUP BY date_format(payment_date,'%M')
ORDER BY FIELD(date_format(payment_date,'%M'),'January','February','March','April','May','June','July','August','September','October','November','December');

同时附上我得到的输出。

子查询,然后在逐月更改字段上添加检查以过滤掉 NULL 条记录。

WITH cte AS (
    SELECT DATE_FORMAT(payment_date, '%M') Month,
           COUNT(*) - LAG(COUNT(*)) OVER (
               ORDER BY FIELD(DATE_FORMAT(payment_date, '%M'),
               'January', 'February', 'March', 'April', 'May', 'June', 'July',
               'August', 'September', 'October', 'November', 'December'))
           AS MonthByMonthChange
    FROM main
    GROUP BY 1
)

SELECT Month, MonthByMonthChange
FROM cte
WHERE MonthByMonthChange IS NOT NULL
ORDER BY FIELD(Month, 'January', 'February', 'March', 'April', 'May', 'June',
                      'July', 'August', 'September', 'October', 'November',
                      'December');