• I'll take that as a no :hehe:

    Anyway, here's what I'm generally trying to do:

    CREATE TABLE testsql (

    cid integer,

    ctime datetime,

    cgm integer);

    INSERT INTO testsql VALUES

    ('1', '2012-01-01 07:00', '1'),

    ('1', '2012-01-01 07:01', '1'),

    ('1', '2012-01-01 07:02', '1'),

    ('1', '2012-01-01 07:03', NULL),

    ('1', '2012-01-01 07:04', NULL),

    ('1', '2012-01-01 07:05', '5'),

    ('1', '2012-01-01 07:06', '5'),

    ('1', '2012-01-01 07:07', '5'),

    ('1', '2012-01-01 07:08', NULL),

    ('1', '2012-01-01 07:09', NULL),

    ('1', '2012-01-01 07:10', NULL),

    ('1', '2012-01-01 07:11', NULL),

    ('2', '2013-05-02 07:12', '24'),

    ('2', '2013-05-02 07:13', '24'),

    ('2', '2013-05-02 07:14', '24'),

    ('2', '2013-05-02 07:15', NULL),

    ('2', '2013-05-02 07:16', NULL),

    ('2', '2013-05-02 07:17', '44'),

    ('2', '2013-05-02 07:18', '44'),

    ('2', '2013-05-02 07:19', NULL),

    ('2', '2013-05-02 07:20', '4'),

    ('2', '2013-05-02 07:21', '4'),

    ('2', '2013-05-02 07:22', '4');

    And here's the query

    WITH C (id, pt, gm, dr) as (

    SELECT cid, ctime, cgm,

    dense_rank() over (partition by cid, cgm order by cid, ctime) as dr

    FROM testsql

    )

    SELECT id, pt, gm,

    CASE WHEN gm IS NULL THEN

    LAG(gm, cast(c.DR as int)) OVER (PARTITION BY id ORDER BY id, pt)

    ELSE gm END as gm2

    FROM C

    ORDER BY id, pt, gm

    There's one result towards the end that is still NULL, rather than being filled in with a LAG value, like the rest in the CASE column are.

    Any suggestions?