如何最后返回具有特定值的行?

use*_*111 5 sql-server t-sql

我的问题与这个问题相反,是否可以定义排序顺序

我想从 SQL Server 数据库返回一些记录,根据列的值按升序排序,但两个特定记录应始终放在最后。

原始SQL(需要更改)如下:

select code_id as CategoryID, code_desc as CategoryDescription
from codes
where code_id > '000001' and code_id < '000100'
order by CategoryDescription
Run Code Online (Sandbox Code Playgroud)

结果返回为

  • 000003 ***第一条记录
  • 000002 ***另一条记录
  • 000004 苹果
  • 000016 书籍
  • 000014 电缆

我想要以下结果(前两个最后一个带有星号):

  • 000004 苹果
  • 000016 书籍
  • 000014 电缆
  • 000003 ***第一条记录
  • 000002 ***另一条记录

我尝试了下面的 UNION 语句,但结果集自动按升序排序,默认情况下这两行在开头。

select code_id as CategoryID, code_desc as CategoryDescription
from codes
where code_id > '000003' and code_id < '000100' 
--order by categoryDescription

UNION

select code_id as CategoryID, code_desc as CategoryDescription
from codes
where code_id > '000001' and code_id < '000004'
Run Code Online (Sandbox Code Playgroud)

Aar*_*and 6

这似乎是比引入一堆联合更简单的解决方案:

SELECT code_id as CategoryID, code_desc as CategoryDescription
FROM dbo.codes
WHERE code_id > '000001' AND code_id < '000100'
ORDER BY CASE code_id
  WHEN '000002' THEN 3
  WHEN '000003' THEN 2 
  ELSE 1 END, CategoryDescription; 
Run Code Online (Sandbox Code Playgroud)