如何按 sql 中的多列排序

How to order by multiple columns in sql

我需要帮助来排序我的结果,可能需要组合使用 case 语句。请查看显示现有输出、条件和所需输出的图像。展览于Excel 是为了方便,但实际完成于SQL。 ORDER BY 子句是我需要帮助的。

select 
distinct 
CONCAT(selection.Selid,' - ' ,Selection.Name,' - ', DevOfficer.Description,' - ', SchemeCount.[Number of Schemes],' Schemes - ',case when selection.Project=1 then '[Project] ' when selection.Project=0 then '[Selection] '  else 'Error' end,convert(varchar,selection.lastupdated,103)) [String]
, selection.selid
, selection.lastupdated 
,case when selection.Project=1 then '[Project]'
when selection.Project=0 then '[Selection]'
else 'Error' end
,selection.lastupdated
from selection 
inner join SelScheme on selection.SelID =selscheme.SelID 
inner join DevOfficer on selection.DevOfficer = DevOfficer.DevOfficerID 
inner join (select selscheme.selid ,count(selscheme.SchemeID) [Number of Schemes] from SelScheme group by SelScheme.SelID) SchemeCount on schemecount.SelID = Selection.SelID 
where selection.masterselid = 0 
order by 
--selection.lastupdated  desc,
case 
when selection.Project=1 then '[Project]'
when selection.Project=0 then '[Selection]' 
 else 'Error' End Desc
 ,selid desc
 ,selection.lastupdated

这是您需要的订单:

order by type desc,
         id desc, 
         case when isdate(last_updated_date) then last_updated_date else 0 end desc 

使用 asc 和 desc 修饰符,为您需要的每个排序列

* 在将代码片段添加到 OP 问题之前回答*

虽然我不确定 SQL table 名称甚至实际的 SQL 字段名称,但下面的方法是可行的。 您需要根据优先级列出 ORDER BY 中的所有字段;

     SELECT
     [ID]
    ,[Type]
    ,[Last Updated Date]
    FROM [SCHEMA].[TABLENAME]
    ORDER BY [Type] ASC, [ID] DESC, [Last Updated Date] DESC