如何在SQL中按任意条件排序

时间:2013-03-22 05:47:26

标签: sql sql-server tsql

我有下表:

CREATE TABLE Bable
    (
     id int identity primary key, 
     name varchar(20), 
     about varchar(30)
    );
INSERT INTO Bable (name,about) VALUES
('ООО Name Firm 1','texttexttexttext'),
('ООО Name Firm 2','texttexttexttext'),
('ООО Name Firm 3','texttexttexttext'),
('ООО Name Firm 4','texttexttexttext'),
('ООО Name Firm 5','texttexttexttext'),
('ООО Name Firm $1','texttexttexttext'),
('ООО Name Firm $2','texttexttexttext'),
('ООО Name Firm $3','texttexttexttext'),
('ООО Name Firm 6','texttexttexttext'),
('ООО Name Firm 7','texttexttexttext')

我可以编写如下查询:

SELECT * FROM Bable WHERE about = 'texttexttexttext'

如何更改此查询以返回已排序的结果,以便首先显示名称中包含“$”的结果,然后显示不包含“$”的结果,然后每个组按name升序排序?

Structure of the table is here

3 个答案:

答案 0 :(得分:17)

SELECT *
FROM   Bable
ORDER  BY CASE WHEN name LIKE '%$..' THEN 0 ELSE 1 END,
          Name 

答案 1 :(得分:2)

您可以对charatindex

执行相同的操作
SELECT * FROM Bable WHERE about = 'texttexttexttext'
Order by Case When CHARINDEX('$',name)>0 Then 0 Else 1 End,name

答案 2 :(得分:2)


select * from Bable 
order by charindex('$',name,0) desc, name asc
SQL Fiddle Demo