在 SQL 服务器中对具有特定值的列进行排序
Sort a column with a particular value up top in SQL Server
我有专栏Name
。我需要在排序的 table 顶部显示 Default Deliverable Submission Notification
,然后是 Almoda、配置文件更新等。如何在 SQL 服务器中对其进行排序。
ID | Name
-------------------
253 | Almoda
2607 | Default Deliverable Submission Notification
44 | profile update
2609 | Single Submitted Deliverable
3608 | Single Unsubmitted Deliverable
45 | Test for all Deliverables
这是我使用的查询
select *
from tblrepos
order by Name
您需要一个单独的排序顺序列,因为按名称排序不会帮助您获得您在顶部提到的项目。默认按字典顺序排序。
向您的 table 添加一个 alternate_sort_order 列,为每一行分配一个值作为您希望它在排序后的位置,然后使用此查询获取结果。
select id, name
from tblrepos
order by alternate_sort_order;
您可以使用 case expression
人为地将特定结果放在结果集中的第一位,例如
select *
from tblrepos
order by
case when [Name] = 'Default Deliverable Submission Notification' then 1 else 0 end desc
, [Name]
SELECT ID, NAME
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY CASE WHEN NAME = 'Default Deliverable Submission Notification' THEN '0' ELSE [NAME] END) AS IDA
, *
FROM tblrepos
) A ORDER BY IDA
我有专栏Name
。我需要在排序的 table 顶部显示 Default Deliverable Submission Notification
,然后是 Almoda、配置文件更新等。如何在 SQL 服务器中对其进行排序。
ID | Name
-------------------
253 | Almoda
2607 | Default Deliverable Submission Notification
44 | profile update
2609 | Single Submitted Deliverable
3608 | Single Unsubmitted Deliverable
45 | Test for all Deliverables
这是我使用的查询
select *
from tblrepos
order by Name
您需要一个单独的排序顺序列,因为按名称排序不会帮助您获得您在顶部提到的项目。默认按字典顺序排序。
向您的 table 添加一个 alternate_sort_order 列,为每一行分配一个值作为您希望它在排序后的位置,然后使用此查询获取结果。
select id, name
from tblrepos
order by alternate_sort_order;
您可以使用 case expression
人为地将特定结果放在结果集中的第一位,例如
select *
from tblrepos
order by
case when [Name] = 'Default Deliverable Submission Notification' then 1 else 0 end desc
, [Name]
SELECT ID, NAME
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY CASE WHEN NAME = 'Default Deliverable Submission Notification' THEN '0' ELSE [NAME] END) AS IDA
, *
FROM tblrepos
) A ORDER BY IDA