Groups | Blog | Home
all groups > sql server (alternate) > september 2003 >

sql server (alternate) : Advance ORDER BY


qwert12345 NO[at]SPAM boxfrog.com
9/7/2003 11:31:48 AM
Hi,

I'm wondering if there's any advance order by 'function'/workaround,
which is reasonably efficient for MS SQL Server, without resorting to
some third party indexing/search engine to achieve the following.

The mechanism is to record each instance of a pattern match and order
by rows with most matches first (DESC). Simplistic match but that's a
separate issue.

Sample:
create table tmp (col varchar(50));
insert into tmp
values ('a barking dog');
insert into tmp
values ('a dog and cat fights over dog food');
insert into tmp
values ('lovable dog is not barking dog=nice dog');

The goal for the Sample is to return resultsets in the following
order:
lovable dog is not barking dog=nice dog -- 3 matches
a dog and cat fights over dog food -- 2 matches
a barking dog -- 1 match

qwert12345 NO[at]SPAM boxfrog.com
9/7/2003 8:45:16 PM
Thank you. Gert-Jan's solution also works.
Can you explain why?

[quoted text, click to view]
Simon Hayes
9/7/2003 8:49:11 PM

[quoted text, click to view]

Here's one possibility:

select col
from tmp
order by len(replace(col, 'dog', '')) desc

Simon

Gert-Jan Strik
9/7/2003 9:06:08 PM
A slight correction on Simon's solution (which will return the longest
string, regardless of number of matches)

select col
from tmp
order by len(col) - len(replace(col, 'dog', '')) desc

Gert-Jan


[quoted text, click to view]
Simon Hayes
9/7/2003 9:08:27 PM

[quoted text, click to view]

Sorry - I posted that a bit too quickly. It should be this - the division by
3 is because your search term has 3 characters, so you can count the number
of replacements made this way:

select col
from tmp
order by (len(col) - len(replace(col, 'dog', ''))) / 3 desc

Simon

Anith Sen
9/8/2003 3:13:21 PM
[quoted text, click to view]

Take the expression used in the ORDER BY clause and add it in the SELECT
list. The answer then becomes obvious.

--
- Anith
( Please reply to newsgroups only )

Gert-Jan Strik
9/8/2003 9:27:18 PM
Of course it does :-)

It works because for the ORDER BY clause you do not need the actual
number of occurrences. You just need them sorted. In that respect "1
barking", "2 dog and cat", "3 lovable dog" is the same as "3 barking",
"6 dog and cat", "9 lovable dog".

Gert-Jan


[quoted text, click to view]
AddThis Social Bookmark Button