Skip to content
Advertisement

Is it Possible to Merge Rows in SQL from Just One Column?

I wonder if it is possible to merge multiple rows from just one column in SQL. Here’s an example of my initial table:

Column 1 | Column 2 | Column 3
______________________________

DAVID    | 10.000   | Client 1
DAVID    | 5.000    | Client 2
DAVID    | 12.000   | Client 3
ANDREW   | 2.000    | Client 4
ANDREW   | 3.000    | Client 5

Here’s my expected output:

Column 1 | Column 2 | Column 3
______________________________

DAVID    | 10.000   | Client 1
         | 5.000    | Client 2
         | 12.000   | Client 3
ANDREW   | 2.000    | Client 4
         | 3.000    | Client 5

I do not know if it’s possible to have a table like the later one. So, any advice would be much appreciated.

Advertisement

Answer

This type of task is usually done in the presentation layer of the application rather than in the database.

But it can be done in SQL – provided that you have a column that defines the ordering of the rows! Say: id.

select
    case when row_number() over(partition by col1 order by id) = 1 then col1 end as col1,
    col2,
    col3
from mytable
order by col1, id
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement