可能重复:
需要对复杂数据排序 SQL Server 的帮助
这是我在 sql server 中的数据,我需要对其进行排序和显示
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
现在我想根据 GEO 和 JCB 等搜索词对数据进行排序
这些行将首先出现在 GEO 或 JCB 在这里找到最长时间 GEO 在 3 行中找到,JCB 在 2 行中找到。所以所有行都有 GEO 关键字,这些关键字将出现在顶部,下一个与 JCB 相关的行将会出现。不匹配的行终于来了。
再次将进行排序。在与 GEO 相关的行中……那些行将首先出现,其中具有最大的 GEO 关键字。相同的 JCB 相关行将被排序。
在这里,我给出的图像将显示我需要什么样的输出
我问了这个问题,得到的答案并没有完全满足我的要求。所以这是我为这个问题得到的sql。
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