简体   繁体   中英

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 naturally 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)

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