MS SQL-如何按通配符排序结果?

时间:2018-07-24 08:01:49

标签: sql sql-server

查询:

SELECT [Name]
  FROM [dbo].[City]
  where name like '%laus%'

结果:

enter image description here

如何排序,以便首先使用通配符(3,4)的记录?

3 个答案:

答案 0 :(得分:3)

尝试一下

;WITH CTE(name )
AS
(
SELECT 'Berlin'         UNION ALL
SELECT 'Laura'          UNION ALL
SELECT 'Losangels'      UNION ALL
SELECT 'Lausanne'       UNION ALL
SELECT 'Lausen'         UNION ALL
SELECT 'Roamanel'       UNION ALL
SELECT 'Sankt Niklaus'  UNION ALL
SELECT 'Vennes sur-Lausanne'

)
SELECT * FROM CTE
ORDER BY (CASE WHEN name like 'Laus%' THEN 1 END ) DESC

结果

name
--------
Lausanne
Lausen
Losangels
Laura
Roamanel
Sankt Niklaus
Vennes sur-Lausanne
Berlin

答案 1 :(得分:3)

您可以尝试,但最好的方法是使用全文搜索

SELECT [Name]
  FROM [City]
  where name like '%laus%'
ORDER BY 
    CHARINDEX('laus',name)

答案 2 :(得分:1)

DECLARE @City TABLE(Name VARCHAR(32))

INSERT @City VALUES
('Belmont-sur-Lausanne'),
('Lausanne'),
('Lausen'),
('Le Mont-sur-Lausanne'),
('Berlin')


SELECT [Name]
  FROM @City
  --where name like '%laus%'
  order by CASE WHEN PATINDEX('%laus%', name) = 0
    THEN LEN(name) 
    ELSE PATINDEX('%laus%', name)
    END
    ,name