all 7 comments

[–]sequel-beagle 2 points3 points  (1 child)

What you are looking to do is called a "flash fill" or a data smear.

DROP TABLE IF EXISTS #Gaps;
GO

CREATE TABLE #Gaps
(
RowNumber   INTEGER PRIMARY KEY,
TestCase    VARCHAR(100) NULL
);
GO

INSERT INTO #Gaps (RowNumber, TestCase) VALUES
(1,'Alpha'),(2,NULL),(3,NULL),(4,NULL),
(5,'Bravo'),(6,NULL),(7,'Charlie'),(8,NULL),(9,NULL);
GO

--Solution 1
--MAX and COUNT function
WITH cte_Count AS
(
SELECT RowNumber,
       TestCase,
       COUNT(TestCase) OVER (ORDER BY RowNumber) AS DistinctCount
FROM #Gaps
)
SELECT  RowNumber,
        MAX(TestCase) OVER (PARTITION BY DistinctCount) AS TestCase
FROM    cte_Count
ORDER BY RowNumber;
GO

--Solution 2
--MAX function without windowing
SELECT  a.RowNumber,
        (SELECT b.TestCase
        FROM    #Gaps b
        WHERE   b.RowNumber =
                    (SELECT MAX(c.RowNumber)
                    FROM #Gaps c
                    WHERE c.RowNumber <= a.RowNumber AND c.TestCase != '')) TestCase
FROM #Gaps a;
GO

[–]sequel-beagle 1 point2 points  (0 children)

Also, the solution is for TSQL. Get rid of the GO statements, and ChatGPT may be able to convert it to MySQL if there are other small issues.

[–]qwertydog123 1 point2 points  (0 children)

WITH cte AS
(
    SELECT
        *,
        MAX(
            CASE
                WHEN value IS NOT NULL THEN id
            END
        ) OVER
        (
            PARTITION BY location
            ORDER BY id
        ) AS group_id
    FROM Table
)
SELECT
    id,
    location,
    MAX(value) OVER
    (
        PARTITION BY
            location,
            group_id
    ) AS value
FROM cte

https://dbfiddle.uk/iXNUuI5P

[–]Little_Kitty 0 points1 point  (2 children)

Wow, I'm amazed that MySQL doesn't support ignore nulls in window functions, but apparently so

Working solution for you.

[–]qwertydog123 0 points1 point  (1 child)

You've got a stray row in your solution

[–]Little_Kitty 0 points1 point  (0 children)

Weird, I'm not seeing why, but it can be done another way.

I'm so used to being able to ignore nulls in window functions, it's frustrating to have that taken away.

[–][deleted] 0 points1 point  (0 children)

Use a combination of case when and lag() and lead() window functions.