具有条件顺序的SQL查询,用于特定条件

时间:2014-06-02 23:06:45

标签: sql sql-server

以下是我的数据的样子

CompanyName   |    CompanyCode
-----------        -----------
                   B190  
ARBOT              B213 
INFRA              A946
MichalesTest       B207
MyCompany          Alerf
MyCompany          lerf
SNELSY             A857
SNELSY             A954

我想将列表CompanyName = 'MyCompany'排序为列表中的第一个,其关联的CompanyCode在ASC中排序。

'MyCompany'之后列出的所有其他项目及其CompanyName在ASC中排序。带有CompanyName的条目可以在列表的末尾。

到目前为止,我已尝试使用以下查询,但我没有得到预期的结果。我正在关注链接here

SELECT [CompanyName], [CompanyCode] FROM  [dbo].COND_ORDERBY_TEST
    ORDER BY CASE CompanyName WHEN 'MyCompany' THEN CompanyName
    ELSE CompanyName END, CompanyCode

我希望我的最终结果设置如下

CompanyName   |    CompanyCode
-----------        -----------
MyCompany           Alerf     
MyCompany           lerf      
ARBOT               B213  
INFRA               A946   
MichalesTest        B207 
SNELSY              A857
SNELSY              A954 
                    B190

我确信应该有一种优雅的方式来做到这一点,但我没有得到它。任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:0)

我会在select中添加一列来解决此问题,然后使用该列进行排序

SELECT [CompanyName], [CompanyCode], 
(CASE WHEN COMPANYNAME='MyCompany' THEN 0 ELSE 1 END) AS SortCol
FROM  [dbo].COND_ORDERBY_TEST
ORDER BY SortCol, CompanyName, CompanyCode

答案 1 :(得分:0)

试试这个

ORDER BY CASE WHEN CompanyName = 'MyCompany' THEN 0 ELSE 1 END,
    CompanyName, CompanyCode

答案 2 :(得分:0)

当我遇到这种情况时,我通常会这样做:

SELECT [CompanyName]
     , [CompanyCode]
     , SortOrder = case when CompanyName is null then 3
                        when CompanyName = 'MyCompany' then 1
                        else 2
                    end
  FROM [dbo].COND_ORDERBY_TEST
 ORDER BY 3 asc, CompanyName asc

由于您始终按相同字段排序,因此SQL Server无法猜测您想要的订单...

尝试一下:)

答案 3 :(得分:0)

      with temp as
        (
       SELECT CompanyName, CompanyCode, 
      CASE WHEN COMPANYNAME='MyCompany' THEN '0' ELSE CompanyName END AS tempcol
      FROM  table name order by CompanyName
      )
      select CompanyName, CompanyCode from temp order by tempcol asc;

答案 4 :(得分:0)

  SELECT [CompanyName], [CompanyCode]
  FROM (
    SELECT [CompanyName], [CompanyCode],
         CASE WHEN CompanyName = 'MyCompany' THEN 1
              WHEN CompanyName is null THEN 3
              ELSE 2 END as orderer
    FROM [dbo].COND_ORDERBY_TEST
  ) T
  ORDER BY orderer ASC, CompanyName ASC