How to add the Second Row to the First row in SQL Server?

Soroush 0 Reputation points
2023-10-10T06:53:40.01+00:00

Hi everyone

I have a question about merging 2 rows into another row.

As you can see in the image below, I have these codes

GS

I need to merge them into one row in SQL Server like this

6262101600808 - 6263017600258

these two codes are just for example, it may be 2 codes or 100 codes. When I execute a query in SQL Server and I get these results, I want to add and merge them to another row.

Thanks in advance.

SQL Server | Other
{count} votes

2 answers

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2023-10-10T06:58:58.8133333+00:00

    Second Row to the First row

    Data don't have a natural order, so there is no "first" and no "second" row, as long as you define explicit an ORDER BY.

    The rest of your post is very vague / unclear.

    Please post table design as DDL, some sample data as DML statement and the expected result.

    0 comments No comments

  2. LiHongMSFT-4306 31,566 Reputation points
    2023-10-10T07:20:15.3533333+00:00

    Hi @Soroush

    these two codes are just for example, it may be 2 codes or 100 codes

    Not sure what you mean, do you want result like this:

    6262101600808 - 6263017600258 - 6262422500184 - 6261717900081 - ......

    If I understand right, then you could use String_agg (SQL Server 2017 (14.x) and later) like this:

    Declare @tbl Table (code varchar(20))
    insert into @tbl values
    ('6262101600808'),('6263017600258'),('6262422500184'),('6261717900081')
    
    SELECT STRING_AGG(code,' - ') Code_list 
    FROM @tbl 
    

    Best regards,

    Cosmog Hong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.