SQL查询结果自定义排序

一般情况之下,我们可以使用ORDER BY ...ASC或DESC来做查询排序。如:

SELECT * FROM [dbo].[SalesPerformance]
ORDER BY [Salesman] ASC

GO

Source Code

如果需要求某一些值先排在前面,其余的数据再按规则排序,如Salesman的值‘S0008’,‘S0032’,‘S0022’排在前3位:

SELECT * FROM [dbo].[SalesPerformance]
ORDER BY CASE 
    WHEN [Salesman] = ‘S0008‘ THEN ‘1‘
    WHEN [Salesman] = ‘S0032‘ THEN ‘2‘
    WHEN [Salesman] = ‘S0022‘ THEN ‘3‘
    ELSE [Salesman] END ASC

Source Code

相关推荐