简体   繁体   中英

SQL Server 2008 - query to order by a column with odd and even numbers

I'm in trouble and I need a quick answer, please.

I have a table in which I have a column containing only odd and even numbers.

I want to select first only the rows with the orderByColumn containing odd numbers, then add the result to the "even query"

My table looks like this

col1   col2   orderByColumn  col4
...................................
 c       c         44          c
 c       c         45          c
 c       c         46          c
...................................
...................................

I guess I should make an union, which I think would look like this:

select * from myTable 
where [orderByColumn] % 2 = 0  --order by [orderByColumn]-->error

UNION

select * from myTable 
where [orderByColumn] % 2 > 0  order by [orderByColumn] 

The query does union the 2 selects, but obviously, they are merged and order by orderByColumn which I don't want to.

I want the results to look like this:

c c 44 c
c c 46 c
c c 48 c
........
c c 45 c
c c 47 c
c c 49 c
........

Any ideas ? Thank you:)

Try this for the even numbers first:

select *
from myTable
order by [orderByColumn]%2, orderbycolumn

Use desc if you want the odd numbers first.

You could also introduce a column with your sort value, like

    select *, 
    case when [orderByColumn]%2=0 then 0 else 1 end as isOdd
    from myTable 
    order by 
    isodd , orderbyColumn

try this

select 
   OrderByColumn 
from 
   table 
where 
  mod(OrderByColumn,2) = 0 

union all 

select 
   OrderByColumn 
from 
   table 
where 
    mod(OrderByColumn,2) >0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM