IF value = ‘x’ then substring

huangapple go评论84阅读模式
英文:

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

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

答案1

得分: 2

你可以使用 CASE 来解决你的问题,代码会如下所示:

  1. SELECT DISTINCT
  2. country,
  3. ID,
  4. Name,
  5. CASE
  6. WHEN country = 'US' THEN SUBSTRING(ID, 3, 5)
  7. ELSE ''
  8. END AS substring
  9. FROM TestTable
英文:

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

  1. SELECT DISTINCT
  2. country,
  3. ID,
  4. Name,
  5. CASE
  6. WHEN country = 'US' THEN SUBSTRING(ID, 3, 5)
  7. ELSE ''
  8. END AS substring
  9. FROM TestTable

huangapple
  • 本文由 发表于 2023年2月23日 19:52:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定