-2

I have an input:

id

1
2
3
4
5
6
7
8
9
10

I want get even and odd columns separately by columns in specified output like this

id col

1  2
3  4
5  6
7  8
9  10

here id and col are separate columns id contains the odd number and col contains the even number for specified input

Shanthi Ponna
  • 11
  • 1
  • 2
  • 1
    If whatever you are working in supports modulus, that will be your answer for sorting. if result mod 2 > 0 then it's a key, else it's a value – Chris Caviness Sep 10 '14 at 19:25
  • Are we assuming your table never has gaps in numbers? What if the next 2 numbers were 11, 13 with no 12? – SQLChao Sep 10 '14 at 19:40

4 Answers4

9
SELECT MIN(id) as id, MAX(id) as col
FROM YourTable
GROUP BY FLOOR((id+1)/2)

For IDs 1 and 2, (id+1)/2 are 2/2 = 1 and 3/2 = 1.5, respectively, and FLOOR then returns 1 for both of them. Similarly, for 3 and 4, this is 2, and so on. So it groups all the input rows into pairs based on this formula. Then it uses MIN and MAX within each group to get the lower and higher IDs of the pairs.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Joined the table on itself

select * 
from yourTable tA
left join yourTable tb on tA.id = (tB.id - 1)
where tA.id % 2 <> 0
SQLChao
  • 7,709
  • 1
  • 17
  • 32
0

To show odd:

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

To show even:

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

Now, just join those two result sets and that's it.

Source

Community
  • 1
  • 1
Hoh
  • 1,196
  • 1
  • 12
  • 30
  • i want that in single query – Shanthi Ponna Sep 10 '14 at 19:30
  • How do you merge these to get the combine results? You need to join them, what is the join condition? (This is a rhetorical question -- the answer is basically the same as the `GROUP BY` condition in my answer.) – Barmar Sep 10 '14 at 19:36
  • @Barmar you're completely right, I posted this answer before I saw yours. I can say that after a lot of years of experience with SQL (not a lot like yours, but still a lot) I could possible never come with such a easy solution like you did. Thanks for teaching me. – Hoh Sep 10 '14 at 19:39
0

If you use SQL you can try:

SELECT CASE WHEN column  % 2 = 1 
            THEN column 
            ELSE null 
       END AS odds,
       CASE WHEN column  % 2 = 2 
            THEN column 
            ELSE null 
       END AS even
FROM yourtable

but not exactl as you ask