[英]SQL query to merge rows based upon sequence defined
I have 2 tables TableA
and TableB
, here is data of both tables 我有2个表
TableA
和TableB
,这是两个表的数据
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
具有相同的计数。
LineSEQNo
(distinct) per row of table LineSEQNo
(distinct) 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
,那么SequenceNumber
为LineSEQNo
将显示和合并CommentText
在基于序列一行。 LineSEQNo
does not exist in TableA
, then desc1
and desc2
will be concatenated for that LineSEQNo
LineSEQNo
不存在TableA
,然后desc1
和desc2
将串联为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.