select id,name from 表 aa
order by (select count(*)
from 表
where ( (charindex('aa',aa.name)>0 and charindex('aa',name)>0) or
(charindex('bb',aa.name)>0 and charindex('bb',name)>0) or
(charindex('cc',aa.name)>0 and charindex('cc',name)>0)
) and id>aa.id )
,(case when (charindex('bb',name)>0 then 0
when (charindex('bb',name)>0 then 1
when (charindex('aa',name)>0 then 2
end )
--tbccc 是我测试时用的表
select id,name from 表 aa
order by (select count(*) from 表 where left(name,2)=left(aa.name,2) and id>aa.id)
,(case left(name,2) when 'cc' then 0
when 'bb' then 1
when 'aa' then 2
end )
再贴一遍
select id,name from 表 aa
order by (select count(*) from tbccc where left(name,2)=left(aa.name,2) and id>aa.id)
,(case left(name,2) when 'cc' then 0
when 'bb' then 1
when 'aa' then 2
end )
--这个不是道,是不是楼主要的结果
select id,name from tbccc aa
order by (select count(*) from tbccc where left(name,2)=left(aa.name,2) and id>aa.id)
,(case left(name,2) when 'cc' then 0
when 'bb' then 1
when 'aa' then 2
end )
/*
9 ccgggggg
5 bbxesabr
8 aannnnn
7 ccrrrrrr
3 bbwwwww
2 aaXXXXXX
6 ccfgfgfg
1 aaXXX
4 ccrddrrrr
create table tb(id numeric(5), name varchar(100))
Insert into tb
select '1','aaXXX'
union all select '2','aaXXXXXX'
union all select '3','bbwwwww'
union all select '4','ccrddrrrr'
union all select '5','bbxesabr'
union all select '6','ccfgfgfg'
union all select '7','ccrrrrrr'
union all select '8','aannnnn'
union all select '9','ccgggggg'
select * from tb order by name desc
--結果
id name
---------------------
7 ccrrrrrr
4 ccrddrrrr
9 ccgggggg
6 ccfgfgfg
5 bbxesabr
3 bbwwwww
2 aaXXXXXX
1 aaXXX
8 aannnnn