IF value = ‘x’ then substring

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

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

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:

确定