简体   繁体   English

SQL Select 语句中的 IFF 语句

[英]IFF statement in SQL Select Statement

I am trying to write an IF statement which will perform the following.....我正在尝试编写一个 IF 语句,它将执行以下操作.....

Here is an example of the results in the table....以下是表中结果的示例....

Name        Exd Name                 RESULT
 HMAA  USA       USA                  HMAA USA
 HMIT  ITL       ITL                  HMIT ITL
 HMTT   LOG       HYT                HMTT LOG (HYT)
 LTYS   LTT      FYM                  LTYS LTT (FYM)
 TTTT   FFF      PPP                 TTTT FFF (PPP)
 FDSE   FGR      FGR                 FDSE FGR

The results should be displayed as follows结果应显示如下

HMTT LOG (HYT) -----as the two names are different I wan to display the Exd NAme in brackets), however when HMAA USA , and the Exd Name is also USA - I only want to display the 'Name', not the Exd Name. HMTT LOG (HYT) -----因为这两个名称不同,我想在括号中显示 Exd NAme),但是当 HMAA USA 并且 Exd 名称也是 USA - 我只想显示“名称”,不是 Exd 名称。

Is this possible in a IF statement....This is my script, as you can see it has the name + Exd Name, however above I would like to incorporate an IIF statement in here to only display as per the above logic.这是否可能在 IF 语句中....这是我的脚本,正如您所看到的,它具有名称 + Exd 名称,但是在上面我想在此处合并一个 IIF 语句以仅按照上述逻辑显示。

SELECT  distinct  RNL.EmplID,
RNL.ServiceType, rnl.[name] + ' ' + '(' + rnl.[Exd Name] + ')' as 'Vessel'
FROM
resultsIB RNL (nolock)

If it's SQL Server you can try:如果是 SQL Server,您可以尝试:

select distinct RNL.EmplID, RNL.ServiceType, 
    rnl.[name] + 
    case 
        when rnl.[name] like '%' + rnl.[Exd Name]
        then ''
        else ' (' + rnl.[Exd Name] + ')'
    end as 'Vessel'
FROM resultsIB RNL (nolock)

or using iif (SQL Server 2012 only AFAIK) ( IIF is a shorthand way for writing a CASE ):或使用iif (仅限 SQL Server 2012 AFAIK)IIF是编写CASE的速记方式):

select distinct RNL.EmplID, RNL.ServiceType, 
    rnl.[name] + 
    iif(rnl.[name] like '%' + rnl.[Exd Name], '', ' (' + rnl.[Exd Name] + ')') as 'Vessel'
FROM resultsIB RNL (nolock)
SELECT distinct  RNL.EmplID, RNL.ServiceType,
       CASE WHEN CHARINDEX(ExdName, Name) = 0
            THEN Name + ' (' + ExdName + ')'
            ELSE Name END AS 'Vessel'
FROM resultsIB RNL (nolock)

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

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