Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Most match result

Status
Not open for further replies.

Bigsin

Programmer
Jan 17, 2009
82
0
0
NL
I'm searching for a query which search for te most match based on the search value '12345678'
The search value must be start from the first number.


My database has to colums

A |B
------------------------
1 |a
12 |b
123 |c
1234 |d
2345678 |e

What I want is the result of column B where the match is 1234. The result must be 'd' in this case

I hope someone can help me with this query.

 
The most what?
The most similar? In that case you would get 2345678.
The longest substring match? would again be 2345678.
The longest substring mathc beginning from the first character?

I don't quite get what exactly you need.

"Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family." (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
try....

Code:
Declare @Search VarChar(20);
Set @Search = '12345678';

Select Top 1 *
From   YourTableNameHere
Where  @Search like ColumnA + '%'
Order By Len(Id) Desc;


-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
@MakeItSo

The first charachter of '12345678' must match with the first character of column a.

So the match can't be '234567'

@gmmastros

Thanks, but not working.




 
I have found what I needed


Declare @Search VarChar(20);
Set @Search = '12345678'

SELECT TOP 1
[a]
,
FROM [database]
WHERE a = SUBSTRing(@Search,1,1) or a = SUBSTRing(@Search,1,2) or a = SUBSTRing(@Search,1,3) or a = SUBSTRing(@Search,1,4)
order by a desc
 
I think Georges code just needs a slight change:

Code:
Declare @Search VarChar(20);
Set @Search = '12345678';

Select Top 1 *
From   YourTableNameHere
Where  @Search like [b]Rtrim[/b](ColumnA) + '%'
Order By Len(Rtrim([b]ColumnA[/b])) Desc;

You fail to even recognize the good idea, your substring conditions only cover cases up to four chars matching, for the general case you would need to continue and it's way more elegant to simply just rtrim.

Bye, Olaf.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top