想象一下,我们有一个表格:
AAA BBB 123
AAA BBB 456
AAA BBB 789
我如何在一行中看到这三个:
AAA BBB 123-456-789(使用分隔符将多个单元格添加到单个单元格中)
干杯。
答案 0 :(得分:1)
试试这个 -
<强>查询:强>
DECLARE @temp TABLE
(
a VARCHAR(10)
, b VARCHAR(10)
, c INT
)
INSERT INTO @temp (a, b, c)
VALUES
('AAA', 'BBB', 123),
('AAA', 'BBB', 456),
('AAA', 'BBB', 789)
SELECT t.a + ' ' + t.b + STUFF((
SELECT '-' + CAST(c AS VARCHAR(10))
FROM @temp t2
WHERE t2.a = t.a
AND t2.b = t.b
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, ' ')
FROM (
SELECT DISTINCT a, b
FROM @temp
) t
<强>输出:强>
AAA BBB 123-456-789
答案 1 :(得分:0)
使用答案found here:
WITH X AS
(
SELECT 'AAA' AS A, 'BBB' AS B, 123 AS C
UNION
SELECT 'AAA' AS A, 'BBB' AS B, 456 AS C
UNION
SELECT 'AAA' AS A, 'BBB' AS B, 789 AS C
)
SELECT DISTINCT
X.A,
X.B,
STUFF((SELECT '-' + CAST(C AS VARCHAR(3)) FROM X FOR XML PATH ('')), 1, 1, '')
FROM
X