【问题标题】:TSQL - How to return rows with a specific value last?TSQL - 如何最后返回具有特定值的行?
【发布时间】: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


【解决方案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

【讨论】:

  • 您必须在最后附加“, CategoryDe​​scription”才能使其完美。
【解决方案2】:
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排序

你的代码太长了为什么不改成这个?

【讨论】:

    【解决方案3】:

    你可以找这个

    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 
    

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多