2

想象一下我们有一张桌子:

AAA BBB 123
AAA BBB 456
AAA BBB 789

我怎样才能在一行中看到这三个:

AAA BBB 123-456-789(使用分隔符将多个单元格添加到单个单元格)

干杯。

4

2 回答 2

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
于 2013-06-11T10:50:27.020 回答
0

使用此处找到的答案:

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
于 2013-06-11T10:51:06.147 回答