patternsqlMinor
Combining multiple rows into single column
Viewed 0 times
rowscombiningcolumnintosinglemultiple
Problem
The return from my MySQL statement displays an example below:
How would I combine the multiple rows to the category column? Like the example below.
id 1 | status | id 2 | name | category
001 | open | 011 | john | person
001 | open | 011 | john | maleHow would I combine the multiple rows to the category column? Like the example below.
id 1 | status | id 2 | name | category
001 | open | 011 | john | person, maleSolution
Below is what you need
---- You have to use
CREATE TABLE customers
([id 1] int, [status] varchar(4), [id 2] int, [name] varchar(4), [category] varchar(6))
;
INSERT INTO customers
([id 1], [status], [id 2], [name], [category])
VALUES
(001, 'open', 011, 'john', 'person'),
(001, 'open', 011, 'john', 'male')
;
select * from dbo.customers---- You have to use
STUFF function with FOR XML PATHselect distinct cs.[id 1]
,cs.[status]
,cs.[id 2]
,cs.[name]
,stuff((
select ',' + c.[category]
from dbo.customers c
where cs.[id 1] = c.[id 1]
for xml path('')
), 1, 1, '') as [category]
from dbo.customers csCode Snippets
CREATE TABLE customers
([id 1] int, [status] varchar(4), [id 2] int, [name] varchar(4), [category] varchar(6))
;
INSERT INTO customers
([id 1], [status], [id 2], [name], [category])
VALUES
(001, 'open', 011, 'john', 'person'),
(001, 'open', 011, 'john', 'male')
;
select * from dbo.customersselect distinct cs.[id 1]
,cs.[status]
,cs.[id 2]
,cs.[name]
,stuff((
select ',' + c.[category]
from dbo.customers c
where cs.[id 1] = c.[id 1]
for xml path('')
), 1, 1, '') as [category]
from dbo.customers csContext
StackExchange Database Administrators Q#94056, answer score: 2
Revisions (0)
No revisions yet.