Search code examples
mysqlsqlwindowsfunctionlag

How show mysql query without NULL?


How show mysql query without NULL?

I want to show my query where "LAG(title) OVER(PARTITION BY emp_no)" IS NOT NULL, I need only titles.emp_no = "LAG(title) OVER(PARTITION BY emp_no)"

My query:

SELECT titles.emp_no, LAG(title) OVER(PARTITION BY emp_no)
FROM titles;

Output:

enter image description here


Solution

  • Subquery your current query and filter based on the lag value:

    WITH cte AS (
        SELECT emp_no, LAG(title) OVER (PARTITION BY emp_no ORDER BY <col>) lag_title
        FROM titles
    )
    
    SELECT emp_no, lag_title
    FROM cte
    WHERE lag_title IS NOT NULL;
    

    Notice that I added an ORDER BY clause to LAG, without which is does not make much sense.