N
N
NataliaCh2019-08-29 12:25:48
SQL
NataliaCh, 2019-08-29 12:25:48

How to write a TSQL query?

There is a table like
num | text
----------------
1 | name1
2 | name2
2 | name3
2 | name4
3 | name5
how to write a query to display data like this
num | all_text
------------
1 | name1
2 | name2, name3, name4
3 | name5

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Planet_93, 2019-08-29
@NataliaCh

Data:
Request:

SELECT
T1.Id,

(SELECT concat(T2.Name, '; ') 
FROM dbo.Test AS T2
WHERE T2.Id = T1.Id
FOR XML PATH('')) AS Name

FROM
dbo.Test AS T1
GROUP BY T1.Id

Result:
5d679dfd51aae997147677.jpeg

L
Lazy @BojackHorseman, 2019-08-29
SQL

STRING_AGG (Transact-SQL)

SELECT num, STRING_AGG(text, ', ') AS all_text
FROM <tablename>
GROUP BY num;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question