-1

I want to display 3 column values into single rows in SQL.

Input:

Branch |Phone1|Phone2|Phone3
abc    |12345 |456321|456321

Output:

Branch|Phone
abc   |12345,456321,45321

Please help

Dale K
  • 25,246
  • 15
  • 42
  • 71
Manish jha
  • 13
  • 1
  • 1
    Does this answer your question? https://stackoverflow.com/questions/25207771/sql-server-how-to-merge-two-columns-into-one-column – VietDD Aug 18 '20 at 06:08
  • 1
    Simply try like `SELECT Branch, Phone1 + ',' + Phone2 +',' + Phone3 AS Phone FROM ....` – Karan Aug 18 '20 at 06:13
  • 1
    Please have a go and only post a question when stuck. We're not here to write your code for you. – Dale K Aug 18 '20 at 06:15
  • 1
    I try to do this using variable and its done. but I have to create 3 variables and its not good that's why I need some alternative solution .so I simply post my question. – Manish jha Aug 18 '20 at 07:04

1 Answers1

1

I would suggest you to leverage CONCAT function & CONCAT_WS function, as they handle NULL values: If there is a NULL value, it is replaced with empty string.

Different approaches are available to do concatenation

SELECT Branch, concat_ws(',',phone1, phone2, phone3) as phone
FROM
(
VALUES
('abc',12345,456321,456321)
) AS T(Branch,Phone1,Phone2,Phone3)
SELECT Branch, concat(phone1,',', phone2,',', phone3) as phone
FROM
(
VALUES
('abc',12345,456321,456321)
) AS T(Branch,Phone1,Phone2,Phone3)
  • Regular concatenation using concatenation operator +
SELECT Branch, cast(phone1 as varchar(10)) + ',' +  cast(phone2 as varchar(10)) + ',' +  cast(phone3 as varchar(10)) as phone
FROM
(
VALUES
('abc',12345,456321,456321)
) AS T(Branch,Phone1,Phone2,Phone3)
  • If there is a possibility of NULL, have ISNULL clause to handle NULLs with empty string.
SELECT Branch, cast(ISNULL(phone1,'') as varchar(10)) + ',' +  cast(phone2 as varchar(10)) + ',' +  cast(phone3 as varchar(10)) as phone
FROM
(
VALUES
('abc',null,456321,456321)
) AS T(Branch,Phone1,Phone2,Phone3)

I would highly recommend CONCAT_WS option, as it makes the code simpler and handles NULLs easily.

Venkataraman R
  • 12,181
  • 2
  • 31
  • 58