简体   繁体   中英

Concatenate two rows value with same id but different column values

在此处输入图像描述
How can I merge multiple rows value with the same ID

When the value in the first and second row in the same column is the same. How can I merge this?

Please see attached image.I want highlighted column

For eg

I want to get the table:

A/b  ID  SUFFIX   Identify No        MERGED id
CON  123     C    12345-33344441-8   123-456
CON2 456     C1   12345-33344441-8   123-456

How can I merge multiple rows values with the same ID?

When the value in the first and second row in the same column is the same. How can I merge this?

For eg

I want to get table:

A/b  ID   SUFFIX   Identify No            MERGED id
CON  123  C        12345-33344441-8       123-456
CON2 456  C1       12345-33344441-8       123-456

I am guessing you want to concat all ID columns for matching IdentityNo
If that is so, you can do it like this

select t.ab,
       t.id,
       t.suffix,
       t.identifyno,
       ( select string_agg(convert(varchar(50), t1.id), '-')
         from   table1 t1
         where  t1.identifyno = t.identifyno
       ) as merged_id
from   table1 t

Try it yourself in this DBFiddle

This approach also has no problem when the rows are ordered in such a way that the matching IdentifyNo are not nice after each other.

Assuming that is what you are after off course

EDIT (after the OP changed the column names)

New DBFiddle

New query

select t.id,
       t.primary_Secondary,
       t.id2,
       t.PassportNO,
       ( select string_agg(convert(varchar(50), t1.id2), '-')
         from   table1 t1
         where  t1.PassportNO = t.PassportNO
       ) as merged_id
from   table1 t

Result from new query

id primary_Secondary id2 PassportNO merged_id
1 Pri 242 12345-789 242-342
2 Sec 342 12345-789 242-342

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM