SQL Help selecting last action of a given event

  • Hi all,

    I'm stuck on a problem which I'd appreciate any help. Given the following table, I want to select the row before the row where Class = '$'. So the result should give me ID 1, 4, and 6. I would like to avoid using Cursors to solve this problem as the number of rows returned will be very large.

    ID             Class

    1              T

    2              $

    3              F

    4              C

    5              $

    6              F

    7              $

    8              $

     

    Thanks,

    Linus

  • Assume id is alwayse increase and has index on it.

    scalar function use max function can help.

    Like

    create function fn_rowbefore$ (@id int)

    returns int

    as

    begin

      declare @ren int

      select @ren = max(id) from tablename where id < @id and class != '$'

      return @ren

    end

    select distinct dbo.fn_rowbefore$(id) from tablename where class = '$'

  • Thanks wz700. That certainly resolve my little problem.

    Cheers,

    Linus

  • As WZ700 said, I'm assuming that ID is a "no skip" sequential IDENTITY column...

    This will "find" everything that meets your criteria all at once in a single run...

    SELECT *

      FROM yourtable

     WHERE ID IN (--Deived table finds the correct ID's

                  SELECT ID-1 AS ID

                    FROM yourtable

                   WHERE Class = '$')

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply