日期:2014-05-18  浏览次数:20571 次

SQL排序 你搞的定不?
说实话,我特不愿意碰到这样的麻烦,但是碰到总是需要解决的,小弟实在无能,没好的经验。希望各位大牛能分享下。

表格TableName 有以下数据

beyond
Billie.Holiday
Bryan Adams
Craig David
Declan Galbraith
Dido
DJ Networx Vol.46
DJ Rap


按模糊条件 D 查询数据,以上数据都是经过筛选的,需要实现的排序是所有D开头的放前面,接着是D放第二位,以此类推。
赢的的结果是
Declan Galbraith
Dido
DJ Networx Vol.46
DJ Rap
beyond
Craig David
Bryan Adams
Billie.Holiday

还望各位大牛不吝赐教

------解决方案--------------------
SQL code

create table tb(col varchar(30))
insert into tb
select 'beyond' union all
select 'Billie.Holiday' union all
select 'Bryan Adams' union all
select 'Craig David' union all
select 'Declan Galbraith' union all
select 'Dido' union all
select 'DJ Networx Vol.46' union all
select 'DJ Rap'
go

select col
from tb
where col like '%d%'
order by charindex('d',col)

drop table tb

/***************

col
------------------------------
Declan Galbraith
Dido
DJ Networx Vol.46
DJ Rap
beyond
Craig David
Bryan Adams
Billie.Holiday

(8 行受影响)

------解决方案--------------------
SQL code
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (col nvarchar(28))
insert into [TB]
select 'beyond' union all
select 'Billie.Holiday' union all
select 'Bryan Adams' union all
select 'Craig David'union all
select 'Declan Galbraith' union all
select 'Dido' union all
select 'DJ Networx Vol.46' union all
select 'DJ Rap'

select * from [TB]

select col
FROM TB
ORDER BY REPLACE(col,'d','[') asc

/*
Declan Galbraith
Dido
DJ Networx Vol.46
DJ Rap
beyond
Billie.Holiday
Bryan Adams
Craig David*/

------解决方案--------------------
SQL code
select * from tablename order by 
case when substring(col,1,1) = 'D' then 1 else 2 end,
case when substring(col,2,1) = 'D' then 1 else 2 end,
case when substring(col,3,1) = 'D' then 1 else 2 end,
...
case when substring(col,n,1) = 'D' then 1 else 2 end

------解决方案--------------------
SQL code
--> 测试数据:#tb
if object_id('tempdb.dbo.#tb') is not null drop table #tb
create table #tb([name] varchar(50))
insert #tb
select 'Declan Galbraith' union all
select 'Dido' union all
select 'DJ NetworxVol.46' union all
select 'DJ Rap' union all
select 'beyond' union all
select 'Craig David' union all
select 'Bryan Adams' union all
select 'Billie.Holiday'

select * from #tb order by charindex('d',name)
select * from #tb order by patindex('d',name)
/*
name
--------------------------------------------------
Declan Galbraith
Dido
DJ NetworxVol.46
DJ Rap
beyond
Craig David
Bryan Adams
Billie.Holiday

(8 行受影响)


*/

------解决方案--------------------
SQL code
select * from #tb order by  replace(name,'d',' ')