2012-07-27 72 views
1

我需要來自數據庫的複雜數據排序的幫助。假設我的數據存儲在表中,如下所示:需要幫助進行復雜的數據排序SQL Server

Description 
-------------- 
JCB Excavator - ECU P/N: 728/35700 
Geo Prism 1995 GEO - ABS #16213899 GEO pump 
Geo Prism 1995 - GEO ABS #16213897 
Geo Prism 1995 - ABS #16213897 
Ersatz Airbags, Gurtstrammer und Auto Körper Teile 
this test JCB pipe & JCB pump 
Wie man BBA reman erreicht 

7行在那裏。我想以這樣的方式編寫SQL查詢,因爲它會根據我的輸入詞對數據進行排序。假設我的搜索詞是GEO,JCB兩個單詞用逗號隔開。最先到達的行是搜索詞找到最大時間的行。所以對於GEO這個詞在大多數行中有最大的時間。

兩類將被要求:

  • 以這樣的方式,其中搜索詞發現的最大時間在前排序數據。
  • 根據每行中發現的搜索詞的最大出現次數對數據進行第二次排序。

假設GEO在最大行中找到的搜索詞。

因此,所有具有GEO關鍵字的行都會先出現,然後JCB的相關數據纔會到來。

GEO相關數據那些行將首先具有最大GEO關鍵字。

所以輸出看起來像。

Description 
-------------- 
Geo Prism 1995 GEO - ABS #16213899 GEO pump 
Geo Prism 1995 - GEO ABS #16213897 
Geo Prism 1995 - ABS #16213897 
this test JCB pipe & JCB pump 
JCB Excavator - ECU P/N: 728/35700 
Ersatz Airbags, Gurtstrammer und Auto Körper Teile 
Wie man BBA reman erreicht 

請幫助我構建這種SQL將在所有SQL Server版本中工作。

+2

你*有*使用SQL Server作爲一個基於文本的搜索引擎(如Luence)可能是一個更好的解決方案。 SQL Server不擅長解析字符串(這是你必須要做的) – Kane 2012-07-27 07:31:16

+0

**所有** SQL Server版本 - 哇 - 多久後? SQL Server 4.2? 6.0? 6.5? 7.0? 2000? ...... – 2012-07-27 08:42:35

+0

我正在使用sql server 2000 ....所以marc_s可以請你幫我。謝謝 – Thomas 2012-07-27 13:36:59

回答

0

在這裏你去

declare @t table(Description varchar(1000)) 
insert into @t 
select 'JCB Excavator - ECU P/N: 728/35700 ' union all 
select 'Geo Prism 1995 GEO - ABS #16213899 GEO pump ' union all 
select 'Geo Prism 1995 - GEO ABS #16213897 ' union all 
select 'Geo Prism 1995 - ABS #16213897 ' union all 
select 'Ersatz Airbags, Gurtstrammer und Auto Körper Teile ' union all 
select 'this test JCB pipe & JCB pump ' union all 
select 'Wie man BBA reman erreicht' 

declare @search_term varchar(100) 
set @search_term ='GEO' 
select Description from @t 
order by len(Description)-len(replace(Description,@search_term,'')) desc 

結果

Description 
---------------------------------------------------------- 
Geo Prism 1995 GEO - ABS #16213899 GEO pump 
Geo Prism 1995 - GEO ABS #16213897 
Geo Prism 1995 - ABS #16213897 
Ersatz Airbags, Gurtstrammer und Auto Körper Teile 
this test JCB pipe & JCB pump 
Wie man BBA reman erreicht 
JCB Excavator - ECU P/N: 728/35700 
+0

我的搜索詞也可能是多個單詞用逗號隔開,如search_term ='GEO,JCB' – Thomas 2012-07-27 09:14:27

+0

這是不正確的....你沒有使用group by。 – Thomas 2012-07-27 14:42:24