lehoon
lehoon

Reputation: 1

How to concatenate rows with ORDER BY

Edited: In SQL, I’m joining a table with a text column to a separate table (the latter not depicted in my example below). I would like to display the text from each row concatenated as a single column in a row. Using a separate column (Line), I’d like to use to determine the order in which the text is concatenated.

Col   Line   Text
a     1      This
a     4      sentence
a     3      a
a     2      is

Output in a single column/row:

This is a sentence

Upvotes: 0

Views: 1034

Answers (2)

David Sugar
David Sugar

Reputation: 1236

Try this in postgresql:

select  string_agg(Str,' ' order by Line ) as Sentence FROM Table1
group by Col;

Output:

sentence
This is a sentence

http://sqlfiddle.com/#!17/e84f9/4

Upvotes: 1

David Sugar
David Sugar

Reputation: 1236

In MySql try:

select  group_concat(Str order by Line separator ' ' ) as Sentence FROM Table1
group by Col;

Result:

sentence
This is a sentence

http://sqlfiddle.com/#!9/e84f9e/5

Upvotes: 1

Related Questions