开发者

MULTIPLE SELECTS - SAME TABLE

Here goes...

I have 5 records in a table entitled MyTable with a single field called Se. The 5 records contain the following values (1-5):

se=1 se=2 se=3 se=4 se=5

I want to have the records returned to me as follows:

SELECT * FROM MyTable WHERE se >= 3
UNION
SELECT * FROM MyTable WHERE se < 3
ORDER BY se ASC

My objective is to get records returned as:

3,4,5,1 2

but natura开发者_开发技巧lly I get...

1,2,3,4,5

Can you help me? Can MSSQL Server even do this?

Thanks in advance for any assistance.


Try this

SELECT 1, * FROM MyTable WHERE se >= 3
UNION ALL
SELECT 2, * FROM MyTable WHERE se < 3
ORDER BY 1, se ASC


You can use a single select and a condition in the sorting:

select *
from MyTable
order by (case when se >= 3 then 0 else 1 end), se

(The parentheses around the case is not needed, I just added them to make the code clearer.)


If you're looking for a hack for that specific scenario:

SELECT * FROM MyTable ORDER BY (se + 2) % 5

Example on PostgreSQL:

$ WITH MyTable(se) AS (VALUES
$     (1), (2), (3), (4), (5)
$ )
$ SELECT * FROM MyTable ORDER BY (se + 2) % 5;
 se
----
  3
  4
  5
  1
  2
(5 rows)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜