Solved

SQL Order by 'starts with' then by 'contains'

Posted on 2010-11-11
8
563 Views
Last Modified: 2012-05-10
I have an autocompleter for an ecommerce site where customers can enter text (@usrstr) and the query will return either products that start with that text or product categories that contain that text. The results are sorted alphabetically.  I want the results to sort first by records that start with the user's text then by records that contain that text.
If a customer enters in 'M', then results might look like
Combustion Motor
Damper
M2942-110
M2942-111
Motors
Sump Pumps

Currently Returns:
Combustion Motor
Damper
M2942-110
M2942-111
Motors
Sump Pumps

--Desired Result
M2942-110
M2942-111
Motors
Combustion Motor
Damper
Sump Pumps

-- Current Query
(SELECT TOP 5 itm_num
  FROM item
WHERE itm_num like @usrstr + '%')
union
(SELECT DISTINCT TOP 5 ctg_name
  FROM category
WHERE ctg_name like '%' + @usrstr + '%')

--Attempt at Desired Result Set
(SELECT TOP 5 itm_num
  FROM item
WHERE itm_num like @usrstr + '%')
union
(SELECT DISTINCT TOP 5 ctg_name
  FROM category
WHERE ctg_name like @usrstr + '%')
union
(SELECT DISTINCT TOP 5 ctg_name
  FROM category
WHERE ctg_name like '%' + @usrstr + '%')


In the end the query can only return one column of data.  Any help is appreciated.
0
Comment
Question by:mjmetzger
  • 4
  • 3
8 Comments
 
LVL 16

Accepted Solution

by:
EvilPostIt earned 500 total points
ID: 34112975
You could try the following..

SELECT SearchTitle FROM
(SELECT TOP 5 itm_num as 'SearchTitle'
  FROM item
WHERE itm_num like @usrstr + '%'
union
SELECT DISTINCT TOP 5 ctg_name as 'SearchTitle'
  FROM category
WHERE ctg_name like '%' + @usrstr + '%')A
ORDER BY CHARINDEX(@usrstr,SearchTitle)
0
 
LVL 18

Expert Comment

by:deighton
ID: 34113000
use a case statement to calculate a field as 0 for first character is 'M' and 1 otherwise

then select all fields containing M and order by your calculated field.

here is an example on one of my tables, here using surname sort as an illustration

note quotes around calculated field 'init' in the sort - I find you need those

SELECT [EmployeeId],    
      [Surname]
      ,CASE SUBSTRING(SURNAME,1,1) WHEN 'M' THEN  0 ELSE 1 END as init
  FROM MyMaster
  WHERE SURNAME LIKE '%M%'
  ORDER BY 'init', surname
0
 
LVL 16

Expert Comment

by:EvilPostIt
ID: 34113013
This will also order based upon how close to the begining of the string the original search is. For example if the user searched for M they would get

MXXXXX
XMXXXX
XXMXXX
XXXMXX
XXXXMX
XXXXXM

You you want to further order these results with the matching position you could also do ORDER BY CHARINDEX(@usrstr,SearchTitle),SearchTitle
0
 

Author Closing Comment

by:mjmetzger
ID: 34113122
Creative Solution!  
0
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 

Author Comment

by:mjmetzger
ID: 34113170
EvilPostIt, what is the purpose of that 'A' after the parenthesis? I thought it was a typo at first, but the query won't run without it.  Aparently the character itself is arbitrary, but i've never seen it before.
0
 
LVL 16

Expert Comment

by:EvilPostIt
ID: 34113183
You have to alias the table when using subqueries. If you were to do a join there would be no way to refer to that table as it does not have a name.
0
 
LVL 16

Expert Comment

by:EvilPostIt
ID: 34113198
You can call it anything you like. I just chose A cause i was being last. You could call it BLAHBLAH if you really liked.
0
 

Author Comment

by:mjmetzger
ID: 34113373
perfect. thanks again!
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now