SELECT N rows before and after the row matching the condition?

前端 未结 6 1727
暗喜
暗喜 2021-02-02 15:02

The behaviour I want to replicate is like grep with -A and -B flags . eg grep -A 2 -B 2 \"hello\" myfile.txt will give me all the lines wh

6条回答
  •  无人及你
    2021-02-02 15:50

    (MS SQL Server only)

    The most reliable way would be to use the row_number function that way it doesn't matter if there are gaps in the id. This will also work if there are multiple occurances of the search result and properly return two above and below each result.

    WITH
    
    srt AS (
        SELECT ROW_NUMBER() OVER (ORDER BY id) AS int_row, [id]
        FROM theTable
    ),
    
    result AS (
        SELECT int_row - 2 AS int_bottom, int_row + 2 AS int_top
        FROM theTable
            INNER JOIN srt
                ON theTable.id = srt.id
        WHERE ([message] like '%hello%')
    )
    
    SELECT theTable.[id], theTable.[message]
    FROM theTable
        INNER JOIN srt
            ON theTable.id = srt.id
        INNER JOIN result
            ON srt.int_row >= result.int_bottom
            AND srt.int_row <= result.int_top
    ORDER BY srt.int_row
    

提交回复
热议问题