Skip to content
Advertisement

MySQL ignore NULL Value while using LAG() function

I want to calculate the MonthByMonth difference of payments happening throughout the year. For example, if I had 100 payments in February & 120 in the month of March, the difference would be 20. I have already made a query that uses LAG(), but the only problem I’m facing is that the query is showing NULL Value. Since there are no payments before February, the MonthByMonth would show NULL, I WANT TO SKIP THAT ROW. Below is the sample Dataset

Sample Dataset

And this is the query I’m using

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

Also attaching the output I’m getting.

Sample Output

Advertisement

Answer

Subquery and then add a check on the month by month change field to filter off NULL records.

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');
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement