使用case语句的SQL连接
我有一张这样的桌子:使用case语句的SQL连接,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一张这样的桌子: **ID col1 col2 col3 col4 col5** 1 abc NULL NULL NULL NULL 2 ght cde NULL NULL NULL 3 atr dgf aft NULL NULL 4 asd rty tyu xyz NULL 5 abc pqr xyz rst
**ID col1 col2 col3 col4 col5**
1 abc NULL NULL NULL NULL
2 ght cde NULL NULL NULL
3 atr dgf aft NULL NULL
4 asd rty tyu xyz NULL
5 abc pqr xyz rst rty
6 qwe rty ghj rty tyu
我想用以下表格更改:
**ID NewCol**
1 abc
2 ght/cde
3 atr/dgf/aft
4 asd/rty/tyu/xyz
5 abc/pqr/xyz/rst/rty
6 qwe/rty/ghj/rty/tyu
我写的查询是:
SELECT ID,
NewCol = CASE WHEN col1 IS NOT NULL AND col2 IS NULL THEN col1
WHEN col1 IS NOT NULL AND col3 IS NULL THEN col1+'/' + col2
WHEN col1 IS NOT NULL AND col4 IS NULL THEN col1+'/'+ col2 + '/' + col3
WHEN col1 IS NOT NULL AND col5 IS NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4
WHEN col1 IS NOT NULL AND col5 IS not NULL THEN col1+'/' + col2 + '/' + col3+ '/' + col4 + '/' + col5
ELSE NULL
END
FROM dbo.Temp
如果我们有10个专栏,那么我想这可能不是一个有效的写作方式。你能帮我找到更好的解决办法吗?
谢谢。我认为这更简单:
select (col1 + coalesce('/' + col2, '') + coalesce('/' + col3, '') +
coalesce('/' + col4, '') + coalesce('/' + col5, '')
)
这假设
col1
总是有一个值。我认为这更简单:
select (col1 + coalesce('/' + col2, '') + coalesce('/' + col3, '') +
coalesce('/' + col4, '') + coalesce('/' + col5, '')
)
这假设col1
总是有一个值。您可以使用
col1 + concat('/' + col2, '/' + col3, '/' + col4, '/' + col5)
如果在2012或更高版本上,您可以使用
col1 + concat('/' + col2, '/' + col3, '/' + col4, '/' + col5)
如果在2012年或更高版本上为空时使用coalesce和concat a“”?聚结(col1)、+“/”聚结(Col2)+“/”。。。然后消除任何尾随的“/”?当为null时使用coalesce和concat a?聚结(col1)、+“/”聚结(Col2)+“/”。。。然后用内部concat消除任何尾随的'/''整洁的想法。当colx为null时,我喜欢'/'+col2结果为null。然后在coalesce Clean.neat idea和内部concat上将null设置为空字符串。我喜欢在colx为null时“/”+col2结果为null。然后在coalesceclean中将null设置为空字符串。