A tricky one

  • Hi

    I have a table of links to images. I have an identity key for a particular image but i want to get the identity value of the image 4 rows beneath it using the current identity value. Is there an SQL statement that could do this?

    Thanks

    Matt

  • Since there is not such thing as row beneath another row, I assume that you meant that you want the identity value that has 3 different values between it and the current identity value that you are looking at. If I'm correct, then you can have a CTE that selects the top 4 records from the table where the ID value is smaller then the ID of your current row order by the ID desc. From the CTE you can select the min(ID). If you would have written a script with the table structure and insert some test data, I would have written a code that demonstrates that.

    Another option if to use ranking functions and get the record number that you want.

    Adi

    --------------------------------------------------------------
    To know how to ask questions and increase the chances of getting asnwers:
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    For better answers on performance questions, click on the following...
    http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • Thanks Adi, I'll give that a go

  • CREATE TABLE tmp(iCol INT identity(1,1), some_col varchar(10))

    GO

    INSERT tmp(some_col) SELECT 'a'

    GO 100

    DELETE FROM tmp

    WHERE iCol % 3 = 0

    GO

    SELECT TOP 5 *

    FROM tmp ORDER BY iCol Desc

    GO

    WITH cte(a) AS (

    SELECT TOP 5 iCol FROM tmp ORDER BY iCol Desc)

    SELECT TOP 1 a FROM cte ORDER BY a

    GO

    SELECT TOP 1 f.iCol

    FROM (

    SELECT TOP 5 iCol FROM tmp ORDER BY iCol Desc) f

    ORDER BY f.iCol

    GO

    DROP TABLE tmp

    GO

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

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