If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Select 'A and B' records first, then 'A or B' records

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 02-23-10, 04:07
gilbutre gilbutre is offline
Registered User
 
Join Date: Feb 2010
Posts: 2
Select 'A and B' records first, then 'A or B' records

Hi everyone,

I have a dynamically generated query containing any number of OR clauses. Let's say I just have one : select A or B. I want SQL to select all records which contain A or B STARTING WITH those which contain both!

If I have two OR clauses, like SELECT A or B or C , then I want SQL to select first and foremost the records which include A and B and C as well, then those which include A and B, those which include B and C and those which include A and C. Then, those which include only A, those which include only B, and those which include only C.

You get the idea. But how to do that ?
Reply With Quote
  #2 (permalink)  
Old 02-23-10, 04:47
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,524
Code:
SELECT foo
     , CASE WHEN foo like 'A%' THEN 1 ELSE 0 END +
       CASE WHEN foo like 'B%' THEN 1 ELSE 0 END +
       CASE WHEN foo like 'C%' THEN 1 ELSE 0 END   AS score
  FROM daTable
ORDER
    BY score
     , foo
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 02-23-10, 08:33
gilbutre gilbutre is offline
Registered User
 
Join Date: Feb 2010
Posts: 2
Works perfectly. Thank you.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On