sql联合查询并合并根据A表合并B表中的字段,请教各位大神
A表:
ID htbh
1 SANAN-XAKY8Q-020130125
2 SANAN-XAKY8Q-20130226
B表
ID jhbh
1 1saxabb-WZJH-2013-DQ8-002
2 1saxabb-WZJH-2013-BZ8-001
2 1saxabb-WZJH-2013-JX8-003
结果
ID NAME RESULT1
1 SANAN-XAKY8Q-020130125 1saxabb-WZJH-2013-DQ8-002
2 SANAN-XAKY8Q-20130226 1saxabb-WZJH-2013-BZ8-001,1saxabb-WZJH-2013-JX8-003
B表有可能只有一条数据与B表关联,也有可能好多条数据与B表关联,
我用
select stuff((select ','+[value] from tb a left join ttb b on a.sid=b.m_sid where id=tb.id for xml path('')), 1, 1, '')
这样的语句发现会把B表中的都相加,请教各位这个怎么写?
------解决方案---------------------_-关键的忘记写了
select a.*,b.jhbh from tbA a inner join
(select id,stuff((select ','+jhbh from tbB where id=x.id for xml path('')),1,1,'') as jhbh from tbB as x group by id)b
on a.id=b.id