对于 SQL Server 2012,您可以通过将 plethora of 替换为COALESCE
single来简化接受的答案CONCAT
:
WITH tests(a, b, c, d) AS (
SELECT NULL, NULL, NULL, NULL UNION
SELECT NULL, NULL, NULL, 'd' UNION
SELECT NULL, NULL, 'c', NULL UNION
SELECT NULL, NULL, 'c', 'd' UNION
SELECT NULL, 'b', NULL, NULL UNION
SELECT NULL, 'b', NULL, 'd' UNION
SELECT NULL, 'b', 'c', NULL UNION
SELECT NULL, 'b', 'c', 'd' UNION
SELECT 'a', NULL, NULL, NULL UNION
SELECT 'a', NULL, NULL, 'd' UNION
SELECT 'a', NULL, 'c', NULL UNION
SELECT 'a', NULL, 'c', 'd' UNION
SELECT 'a', 'b', NULL, NULL UNION
SELECT 'a', 'b', NULL, 'd' UNION
SELECT 'a', 'b', 'c', NULL UNION
SELECT 'a', 'b', 'c', 'd'
)
SELECT a, b, c, d,
STUFF(CONCAT(
'; ' + a,
'; ' + b,
'; ' + c,
'; ' + d
), 1, 2, '') AS cat
FROM tests
a | b | c | d | cat
-----+------+------+------+-----------
NULL | NULL | NULL | NULL | NULL
NULL | NULL | NULL | d | d
NULL | NULL | c | NULL | c
NULL | NULL | c | d | c; d
NULL | b | NULL | NULL | b
NULL | b | NULL | d | b; d
NULL | b | c | NULL | b; c
NULL | b | c | d | b; c; d
a | NULL | NULL | NULL | a
a | NULL | NULL | d | a; d
a | NULL | c | NULL | a; c
a | NULL | c | d | a; c; d
a | b | NULL | NULL | a; b
a | b | NULL | d | a; b; d
a | b | c | NULL | a; b; c
a | b | c | d | a; b; c; d