[英]SQL Server 2008 - query to order by a column with odd and even numbers
我遇到了麻煩,請快速回答。
我有一個表,其中有一個僅包含奇數和偶數的列。
我只想先選擇orderByColumn
包含奇數的行,然后將結果添加到“偶數查詢”
我的桌子看起來像這樣
col1 col2 orderByColumn col4
...................................
c c 44 c
c c 45 c
c c 46 c
...................................
...................................
我想我應該建立一個工會,我認為這樣:
select * from myTable
where [orderByColumn] % 2 = 0 --order by [orderByColumn]-->error
UNION
select * from myTable
where [orderByColumn] % 2 > 0 order by [orderByColumn]
該查詢確實合並了2個選擇,但顯然,它們是由orderByColumn
合並和排序的,我不想這樣做。
我希望結果看起來像這樣:
c c 44 c
c c 46 c
c c 48 c
........
c c 45 c
c c 47 c
c c 49 c
........
有任何想法嗎 ? 謝謝:)
首先嘗試偶數:
select *
from myTable
order by [orderByColumn]%2, orderbycolumn
如果要先使用奇數,請使用desc
。
您還可以使用您的排序值引入一列,例如
select *,
case when [orderByColumn]%2=0 then 0 else 1 end as isOdd
from myTable
order by
isodd , orderbyColumn
嘗試這個
select
OrderByColumn
from
table
where
mod(OrderByColumn,2) = 0
union all
select
OrderByColumn
from
table
where
mod(OrderByColumn,2) >0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.