views:

115

answers:

3

hi

i have a table MEN in sql server 2008 that contain 150 rows.

how i can show only the even or only the odd rows ?

thank's in advance

+3  A: 

Check out ROW_NUMBER()

SELECT t.First, t.Last
FROM (
    SELECT *, Row_Number() OVER(ORDER BY First, Last) AS RowNumber 
            --Row_Number() starts with 1
    FROM Table1
) t
WHERE t.RowNumber % 2 = 0 --Even
--WHERE t.RowNumber % 2 = 1 --Odd
Matthew Whited
Yeah, I didn't have a chance to create a query before I posted that... but I have extended my answer.
Matthew Whited
A: 

Assuming your table has auto-numbered field "RowID" and you want to select only records where RowID is even or odd.

To show odd:

Select * from MEN where (RowID % 2) = 1

To show even:

Select * from MEN where (RowID % 2) = 0
z-boss
YOu can never assume no gaps! There wil be delted records and transactions rolled back.
HLGEM
Never say never. Sometimes you can. For example if you have a static definition table. But the question is not clear to assume anything, so you're right.
z-boss
+1  A: 

Try this :

odd :

select * from( 
SELECT col1, col2, ROW_NUMBER() OVER(ORDER BY col1 DESC) AS 'RowNumber', 
FROM table1
) d where (RowNumber % 2) = 1 

even :

select * from( 
SELECT col1, col2, ROW_NUMBER() OVER(ORDER BY col1 DESC) AS 'RowNumber', 
FROM table1
) d where (RowNumber % 2) = 0
Pranay Rana