英文:
IF value = 'x' then substring
问题
SELECT DISTINCT country, ID, Name --, IF(country = 'US', "SUBSTRING(ID, 3, 5)", " ") AS substring
FROM TestTable
英文:
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
答案1
得分: 2
你可以使用 CASE
来解决你的问题,代码会如下所示:
SELECT DISTINCT
country,
ID,
Name,
CASE
WHEN country = 'US' THEN SUBSTRING(ID, 3, 5)
ELSE ''
END AS substring
FROM TestTable
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论