简体   繁体   English

比较同一行SQL的两列

[英]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 . 仅选择NameLocation都以DART结尾的行。

Exception: if location ends with legacy , include row regardless. 例外:如果位置以legacy结束,则无论如何都包括row。

          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? 如何比较此SQL的同一行的列?

Something like this should work in MySQL, but most likely in other SQLs too: 这样的事情在MySQL中应该可以使用,但在其他SQL中也很有可能:

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. 如果使用Microsoft SQL,则可能必须执行以下操作。 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. 反转字符串,从第一个字符开始使用长度为2的子字符串提取前两个字符,然后再次反转以正确的方式将其放回去。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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