简体   繁体   中英

Compare two columns of same row SQL

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?

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'
    )

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'
     )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM