Group and values from table

LynnXe

I have a table:

Col1   Col2
---    ---
Bar    Val1
Bar    Val2
Bar    Val3
Foo    Val4
Foo    Val5
Foo    Val6

I need to write a query that outputs

Col1         Col2
---    ----------------
Bar    Val1, Val2, Val3
Foo    Val4, Val5, Val6

I need to write it as a single query, so couldn't use COALESCE() for concatenating, as it would require using variable and loop.

My other solution was to use recursive CTE. However, I need to concatenate values for both 'Bar' and 'Foo'. I thought of CROSS APPLY but don't know is it possible to achieve this result with using CROSS APPLY and recursive CTE.

Any suggestions?

Mat Richardson
select distinct 
    Col1,
    (
     select STUFF((select ',' + col2 
     from yourtable b 
     where b.col1 = a.col1 for xml path('')),1,1,'')
     ) as Col2
from yourtable a

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Fill in missing values by group in data.table

From Dev

Rearranging values from a pivot table

From Dev

Insert values from A table to A table

From Dev

Sum values from a table in a loop

From Dev

Group by in data.table in R which only keep non NA values from columns

From Dev

Update table with values from other table

From Dev

tesseract reading values from a table

From Dev

MySQL - Update table values from another table

From Dev

SQL group table values

From Dev

How to group dulicate table values in UL?

From Dev

MySQL - getting an associated list of values from one table in a query with a GROUP BY from another table

From Dev

Get distinct values from table

From Dev

How to obtain trend from a table for the same column values in multiple row that needs group by

From Dev

print out a group of values from a procedure into one table on SQL server 2008

From Dev

Sum by group with multiple logical conditions while omitting values from sum R data.table

From Dev

insert values to a table from watchdog

From Dev

Different values from subset of a table

From Dev

TSQL Count appearance Group by values in other table

From Dev

querying values from the table

From Dev

selecting values from a reference table

From Dev

Group concat the column names from the table based on their row values

From Dev

How to get values from table

From Dev

Grab from table values

From Dev

Group table values and add up the others

From Dev

Fetching a cluster / group of values from a Database Table - Oracle SQL

From Dev

SELECT where group contains values from another table

From Dev

How remove from group in table

From Dev

Get the values from a table of checkboxes

From Dev

Cannot group table values by ID

Related Related

HotTag

Archive