代码之家  ›  专栏  ›  技术社区  ›  Dasal Kalubowila

如何在SQL中按多列排序

  •  -1
  • Dasal Kalubowila  · 技术社区  · 6 年前

    我需要帮助排序我的结果,可能需要结合使用case语句。请参阅显示现有输出、条件和所需输出的图像。在Excel中轻松显示,但实际上是在SQL中完成的。ORDERBY子句是我需要帮助的内容。

    enter image description here

    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
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   DDS    6 年前

    这是您需要的订单:

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

    使用asc和desc修饰符,用于所需的每个按列排序

        2
  •  0
  •   ChrisCarroll    6 年前

    *在代码段添加到op问题之前回答*

    虽然我不确定SQL表名,甚至不确定实际的SQL字段名,但是下面的内容会起作用。 您需要根据优先级按顺序列出所有字段;

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