Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 569
Bijan Avatar asked May 06 '15 19:05

Bijan


People also ask

How do I find the middle element in SQL?

SQL Median. Median refers to the "middle" number in a series of numbers. When the total count is odd, this is pretty straightforward. Assuming there are n numbers, the median number would be the (n+1)/2-th largest number (or the (n+1)/2-th smallest number -- both are the same number).

How do I select the middle row in MySQL?

To select results from the middle of a sorted list, use ORDER BY clause along with LIMIT.


1 Answers

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
like image 195
M.Ali Avatar answered Sep 23 '22 14:09

M.Ali