新人请教1条SQL语句

liushiying18 2016-12-11 06:58:15

有3个表
表1,Tb_Product
ProductID ProductName
00000001 aa
00000002 bb

表2,Tb_ProductStructure
ProductID MaterielTypeID2
00000001 0001-0015
00000001 0001-0001
00000002 0001-0012
00000002 0001-0010
00000002 0002-0002

表3,Tb_MaterielType2
MaterielTypeID2 MaterielTypeID MaterielTypeName2
0001-0001 0001 PE
0001-0010 0001 CPP
0001-0012 0001 PET
0001-0015 0001 ON
0002-0002 0002 PE


想返回下面结果,怎么样实现啊,谢谢
ProductID ProductName MaterielTypeName2
00000001 aa ON/PE
00000002 bb PET/CPP/PE

...全文
529 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xxfvba 2016-12-12
  • 打赏
  • 举报
回复
;with Tb_Product (ProductID , ProductName) as (select '00000001', 'aa' union all select '00000002', 'bb'), Tb_ProductStructure(ProductID, MaterielTypeID2) as (select '00000001', '0001-0015' union all select '00000001', '0001-0001' union all select '00000002', '0001-0012' union all select '00000002', '0001-0010' union all select '00000002', '0002-0002'), Tb_MaterielType2(MaterielTypeID2, MaterielTypeID, MaterielTypeName2) as (select '0001-0001', '0001', 'PE' union all select '0001-0010', '0001', 'CPP' union all select '0001-0012', '0001', 'PET' union all select '0001-0015', '0001', 'ON' union all select '0002-0002', '0002' , 'PE') select a.*, STUFF((select '/'+MaterielTypeName2 from Tb_MaterielType2 c,Tb_ProductStructure b where c.MaterielTypeID2=b.MaterielTypeID2 and a.ProductID=b.ProductID for XML path('')),1,1,'') from Tb_Product a group by a.ProductID,a.ProductName
zbdzjx 2016-12-12
  • 打赏
  • 举报
回复
看一下这个:http://bbs.csdn.net/topics/392062276 将3个表连接,用上面页面中的合并列方式,将MaterielTypeName2列合并。
liushiying18 2016-12-12
  • 打赏
  • 举报
回复
为什么要加上group by a.ProductID,a.ProductName

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧