我正在尝试在SQL查询中实现串联。我需要使用逗号作为值之间的分隔符。
select concat(technology,',',secondary_technology,',',tertiary_technology) as Technology from deals
这完全正常。但是,如果第二级和第三级技术列中没有值,则结果看起来像
Blue Prism,,
因此,如果二级和三级技术为空,则需要设定一个条件,然后需要省略逗号。 我正在使用以下查询:
select concat(technology,if(secondary_technology is null,'',','),secondary_technology,if(tertiary_technology is null,'',','),tertiary_technology) as Technology from deals
但这会引发错误提示 关键字“ if”附近的语法不正确。 ','附近的语法不正确。
请帮助我! 我正在使用MS SQL Server 2014 谢谢你。
答案 0 :(得分:2)
在添加时,Concat将忽略NULL值。试试这个
select CONCAT(technology, ',' +secondary_technology, ',' +tertiary_technology)
from deals
如果技术列可以为空。
select case when technology is null then stuff(Result, 1, 1, '') else Result end
from (
select technology, CONCAT(technology, ',' +secondary_technology, ',' +tertiary_technology) as Result
from deals
) tab
您可能还想使用NULLIF检查空字符串列。
select case
when coalesce(technology,'') = '' then stuff(Result, 1, 1, '')
else Result
end Result
from
(
select technology
, CONCAT(technology, ',' + nullif(secondary_technology,''), ',' + nullif(tertiary_technology,'')) as Result
from deals
) tab
答案 1 :(得分:1)
使用coalesce()
:
select concat(technology, coalesce(',' +secondary_technology, ''), coalesce(',' +tertiary_technology, '')) as Technology
from deals;
编辑:使用stuff()
:
select stuff(<concat query> 1,1, '')
from deals;
答案 2 :(得分:0)
请使用以下代码作为替代:
SELECT CONCAT(技术,ISNULL(第二技术,''),ISNULL(第三技术,''))AS技术
来自交易;
答案 3 :(得分:0)
尝试:
select concat(
technology,
CASE WHEN secondary_technology IS NOT NULL
THEN concat(', ', secondary_technology)
ELSE ''
END,
CASE WHEN tertiary_technology IS NOT NULL
THEN concat(', ', tertiary_technology)
ELSE ''
END,
) as Technology
from deals;
请参阅与此问题相关的以下答案:https://stackoverflow.com/a/19242830/3554534