当前位置: 代码迷 >> Sql Server >> 怎么通过表a得到表b
  详细解决方案

怎么通过表a得到表b

热度:36   发布时间:2016-04-24 20:29:12.0
如何通过表a得到表b


就是把每个人对应的课程用逗号连起来,求指教谢谢

------解决方案--------------------



if object_id('Tempdb..#t') is not null drop table #t
create table #t(
id int identity(1,1) not null,
lastname nvarchar(100) null,
lession nvarchar(100) null
)
Insert Into #t
select '张三','数学' union all
select '张三','语文' union all
select '李四','数学' union all
select '张三','英语' union all
select '王五','语文' union all
select '李四','语文' union all
select '张三','物理'

select t.lastname,stuff((select ','+lession from #t z where z.lastname=t.lastname for xml path('')),1,1, '')
from #t t group by lastname
 
-----------------

(7 行受影响)
lastname                                                                                             
---------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------
李四                                                                                                   数学,语文
  相关解决方案