简体   繁体   English

SQL查询根据定义的序列合并行

[英]SQL query to merge rows based upon sequence defined

I have 2 tables TableA and TableB , here is data of both tables 我有2个表TableATableB ,这是两个表的数据

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

And TableB as below 和TableB如下

    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.. 现在我要从TableB输出..我的意思是输出应该与TableB具有相同的计数。

  1. There will be one LineSEQNo (distinct) per row of table 每行表格将有一个LineSEQNo (distinct)
  2. TableB.LineSEQNo will check in TableA for that LineSEQNo . TableB.LineSEQNo将在TableA检查该LineSEQNo If it exists in TableA , then the SequenceNumber for that LineSEQNo will be shown and merge CommentText in one row based upon sequence. 如果在存在TableA ,那么SequenceNumberLineSEQNo将显示和合并CommentText在基于序列一行。
  3. If that LineSEQNo does not exist in TableA , then desc1 and desc2 will be concatenated for that LineSEQNo 如果LineSEQNo不存在TableA ,然后desc1desc2将串联为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.. 现在,对于解决方案,唯一的解决方案是WHILE循环。

Is there any other way I can get this desired result without a loop? 有没有其他方法可以让我获得所需的结果而无需循环?

The hard part is concatenating the strings for tablea. 困难的部分是串联tablea的字符串。 You can do this in a subquery and then use left join and finish the logic with a coalesce() : 您可以在子查询中执行此操作,然后使用left join并通过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. 是一个SQL Fiddle,它显示了基本思想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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