【发布时间】:2017-03-24 05:56:27
【问题描述】:
我的问题与这个问题相反。
TSQL - Is it possible to define the sort order?
我想从 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
结果返回为
- 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'
【问题讨论】:
-
请展示一些示例数据和预期输出
-
首先在 ORDER BY 中,使用 CASE 表达式将两个特定值放在最后。然后按列排序。
-
你能提供一个样本表和你需要的结果吗?
-
@jarlh 我知道如何以 ORDER BY 的形式强制将一些值放在首位,但从未见过将一些值放在最后的代码。你能告诉我。
-
@Dheeraj Sharma 提供
标签: sql sql-server