1

I have a table sample that looks like :

KeyID   Name    ID    Location  
--------------------------------------------
20063   A DA    20439     AEP  DA           
20063   A DA    20063     APS DA            
20063   A DA    20032     APS RT          
20063   A RT    20032     APS RT          
20063   B RT    20032     APS DA Legacy       

Only select rows where Name and Location both ends with either DA or RT.

Exception: if location ends with legacy , include row regardless.

          20063 A DA    20439     AEP  DA           
          20063 A DA    20063     APS DA    
          20063 A RT    20032     APS RT
          20063 B RT    20032     APS DA Legacy 

How do I compare column of same row for this SQL?

3
  • Is it always the last 2 letters? Commented Apr 7, 2014 at 17:16
  • Yes. Always the last 2 letters. Commented Apr 7, 2014 at 17:16
  • Which DBMS are you using? Postgres? Oracle? Commented Apr 7, 2014 at 19:51

2 Answers 2

2

Something like this should work in MySQL, but most likely in other SQLs too:

SELECT * FROM TABLE
WHERE location like '% Legacy'
    OR (
        SUBSTRING(name,-2)='DA' AND SUBSTRING(location,-2)='DA'
        OR
        SUBSTRING(name,-2)='RT' AND SUBSTRING(location,-2)='RT'
    )
Sign up to request clarification or add additional context in comments.

Comments

0

if using Microsoft SQL you may have to do something like this. You reverse the string, pull the first 2 characters using substring from the first character with a length of 2, then reverse it again to put it back the right way.

SELECT * FROM TABLE 
WHERE location like '% Legacy'
     OR
     (
            reverse(substring(reverse(name),1,2))='DA' 
            AND 
            reverse(substring(reverse(location),1,2))='DA'
        OR
            reverse(substring(reverse(name),1,2))='RT' 
            AND 
            reverse(substring(reverse(location),1,2))='RT'
     )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.