Search code examples
sql-serversql-server-2012

Select Middle Rows in SQL Server


I have a table where I want to select the last 10% of rows, offset by 10% (so I want to select the last 80-90% of the data).

I wrote the following query

SELECT TOP 10 PERCENT
   [col1], [col2]
FROM [table]
ORDER BY [col1] DESC
OFFSET 10 ROWS

But I receive the following error:

Line 5: Incorrect syntax near 'OFFSET'.

What am I doing wrong? I am using Microsoft SQL Server 2012 which should be compatible with OFFSET


Solution

  • Try something like this....

    SELECT TOP (50) PERCENT *
    FROM (
            SELECT TOP (20) PERCENT 
                          [col1]
                         ,[col2]
            FROM [table]
            ORDER BY [col1] DESC
         )T
    ORDER BY [col1] ASC