Avinash Raina Avinash Raina - 7 months ago 16
SQL Question

Get the alternate rows in SQL

I have a table

PERSON
with a single column
GENDER
, and values in 6 rows is like:

GENDER

M
M
M
F
F
F


The output should be like

GENDER

M
F
M
F
M
F


What should be the SQL query to get such output? I believe
ROWNUMBER()
must be used.

Answer
SELECT GENDER, R = ROW_NUMBER() OVER (PARTITION BY GENDER ORDER BY GENDER)
FROM   PERSON
ORDER BY R, GENDER DESC