IF value = 'x' then substring

lstz6jyr  于 2023-02-28  发布在  其他
关注(0)|答案(1)|浏览(104)

I am looking to output the substring where country = 'us' only and leave the substring blank for all other countries. I have tried the below commented-out part but I am not sure my structure/logic is correct. Any help would be great

SELECT DISTINCT country,   ID, Name --, IF(country ='US', "SUBSTRING(ID, 3, 5)", " " ) AS substring
FROM TestTable
2fjabf4q

2fjabf4q1#

As @Squirrel mentioned in the comments you can use CASE to fix your issue, the code then would look like this:

SELECT DISTINCT
    country,
    ID,
    Name,
    CASE
        WHEN country = 'US' THEN SUBSTRING(ID, 3, 5)
        ELSE ''
    END AS substring
FROM TestTable

相关问题