Possible Duplicate:
Need help for complex data sort SQL Server
this is my data in sql server which i need to sort and display
Table : MyTable
------------------
ID Title
-----------
1 Geo Prism GEO 1995 GEO* - ABS #16213899
2 Excavator JCB - ECU P/N: 728/35700
3 Geo Prism GEO 1995 - ABS #16213899
4 JCB Excavator JCB- ECU P/N: 728/35700
5 Geo Prism GEO,GEO 1995 - ABS #16213899 GEO
6 Maruti gear box #ABS 4587
now i want to sort data based on the search term like GEO & JCB
those rows will come first where GEO or JCB found maximum time here GEO found in 3 rows and JCB found in 2 rows. so all rows have GEO keyword those will come at top and next JCB related rows will come. unmatch row will come at last.
again there will be sorting. in GEO related rows...those rows will come first which has maximum GEO keyword. the same JCB related rows will be sorted.
here i am giving the images which will show what kind of out i need
i asked this question and got answer which does not full fill my requirement fully. so here is the sql i got for this question.
CREATE FUNCTION [dbo].[Split] (@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
DECLARE @Sterm varchar(MAX)
SET @Sterm ='GEO JCB'
;WITH SearchResult (rnum, title)
as
(
(select 1 as rnum,'Geo Prism GEO 1995 GEO* - ABS #16213899' as title)
union all
(select 2 as rnum,'Excavator JCB - ECU P/N: 728/35700' as title)
union all
(select 3 as rnum,'Geo Prism GEO 1995 - ABS #16213899' as title)
union all
(select 4 as rnum,'JCB Excavator JCB- ECU P/N: 728/35700' as title)
union all
(select 5 as rnum,'Geo Prism GEO,GEO 1995 - ABS #16213899 GEO' as title)
union all
(select 6 as rnum,'dog' as title)
)
select rnum, title from SearchResult
join
( select lower(Items) as term
from dbo.Split(@Sterm , ' ')
) as search_terms
on lower(SearchResult.title) like '%' + search_terms.term +'%'
order by
search_terms.term,
(select count(*)
from dbo.Split(lower(SearchResult.title),' ')
where Items = search_terms.term
) desc