2

Imagine we have a table as:

AAA BBB 123
AAA BBB 456
AAA BBB 789

How can i see these three in a single row as:

AAA BBB 123-456-789 (multiple cells are added to a single cell using a delimiter)

Cheers.

1

2 Answers 2

0

Using the answer 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
Sign up to request clarification or add additional context in comments.

Comments

0

Try this one -

Query:

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

Output:

AAA BBB 123-456-789

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.