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

时间:2016-11-10 09:07:25

标签: sql sql-server

我的问题与此问题相反。

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 Apple
  • 000016书籍
  • 000014电缆

我想要下面的结果(前两个带有星号的星号):

  • 000004 Apple
  • 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'

3 个答案:

答案 0 :(得分:1)

如果您希望维持联盟,那么您可以这样做:

select * from (
    select 'T' as Success,  code_id as CategoryID, code_desc as CategoryDescription, 1 as order
    from codes
    where code_id > '000003' and code_id < '000100' 

    UNION

    select 'T' as Success,  code_id as CategoryID, code_desc as CategoryDescription, 2 as order
    from codes
    where code_id > '000001' and code_id < '000004'
) x
order by x.order

答案 1 :(得分:0)

select 'T' as Success,  code_id as CategoryID, code_desc as CategoryDescription
from codes
where (code_id > '000003' and code_id < '000100') or (code_id > '000001' and code_id < '000004')

按code_id desc排序

您的代码太长,为什么不将其更改为此?

答案 2 :(得分:0)

你可能正在寻找这个

select 'T' as Success,  code_id as CategoryID, code_desc as CategoryDescription
from codes
where (code_id > '000003' and code_id < '000100') OR 
      (code_id > '000001' and code_id < '000004') 
ORDER BY CASE
           WHEN (code_id > '000003' and code_id < '000100') THEN 1
           WHEN (code_id > '000001' and code_id < '000004') THEN 2
         END 
相关问题