简体   繁体   中英

SQL query to merge rows based upon sequence defined

I have 2 tables TableA and TableB , here is data of both tables

OrderNumber LineSEQNo   SequenceNumber  CommentText
2145106     0000000001      000           ABB -
2145106     0000000001      001           2" AL. pole 7'8"    

And TableB as below

    SalesOrderNumber    LineSEQNo       desc1           desc2
      2145106           0000000001      ORDER DIDN't     NULL
      2145106           0000000002      ABB              BCC                                      
      2145106           0000000003      NULL             Customer did NOT get any.  

Now I want output from TableB .. I mean output should have same count as TableB have..

  1. There will be one LineSEQNo (distinct) per row of table
  2. TableB.LineSEQNo will check in TableA for that LineSEQNo . If it exists in TableA , then the SequenceNumber for that LineSEQNo will be shown and merge CommentText in one row based upon sequence.
  3. If that LineSEQNo does not exist in TableA , then desc1 and desc2 will be concatenated for that LineSEQNo

So output should look like this:

2145106 0000000001      ABB - 2" AL. pole 7'8"
2145106 0000000002      ABB BCC
2145106 0000000003      Customer did NOT get any.  

Hope I made it clear.

Now for solution only solution that is coming in my kind is WHILE loop..

Is there any other way I can get this desired result without a loop?

The hard part is concatenating the strings for tablea. You can do this in a subquery and then use left join and finish the logic with a coalesce() :

select b.*,
       coalesce(a.commenttext, coalesce(desc1, '') + coalesce(desc2, '')       
from tableb b left join
     (select a.ordernumber, a.lineseqno,
             (select a2.commenttext as commenttext
              from tablea a2
              where a2.ordernumber = a.ordernumber and a2.lineseqno = a.lineseqno
              for xml path (''), TYPE
             ).value('.[1]', N'varchar(max)') as commenttext
      from tablea a
      group by a.ordernumber, a.lineseqno 
     ) a
     on b.ordernumber = a.ordernumber and b.lineseqno = a.lineseqno;

Here is a SQL Fiddle that shows the basic idea.

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