----------------------------------------------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2014-07-02 10:16:10
-- Version:
--      Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) 
-- Feb 10 2012 19:13:17 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[学生表]
if object_id('[学生表]') is not null drop table [学生表]
go 
create table [学生表]([ID] int,[名称] varchar(4))
insert [学生表]
select 1,'小王' union all
select 2,'小张' union all
select 3,'小李'
--> 测试数据:[学生专业表]
if object_id('[学生专业表]') is not null drop table [学生专业表]
go 
create table [学生专业表]([ID] int,[学生ID] int,[专业名称] varchar(10))
insert [学生专业表]
select 1,1,'计算机' union all
select 2,1,'商务英语' union all
select 3,2,'电子自动化' union all
select 4,2,'原子信息' union all
select 5,3,'对外贸易'
--------------开始查询--------------------------
;with f as
(
select a.id,a.名称,b.专业名称 from [学生表] as a inner join [学生专业表] as b on a.ID=b.学生ID
)select id,名称,[专业名称]=stuff((select ','+[专业名称] from f where id=t.id for xml path('')), 1, 1, '') 
from f as t
group by id,名称
----------------结果----------------------------
/* id          名称   专业名称
----------- ---- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1           小王   计算机,商务英语
2           小张   电子自动化,原子信息
3           小李   对外贸易(3 行受影响)*/

解决方案 »

  1.   

    楼上的可以
    但能不能写成像
    select ID,名称,(select top 1 专业 from 专业表 where 学生ID = ID) From 学生
    这样方式的,而不是GroupBy的呢?
      

  2.   

    select ID,名称
    ,(select  专业名称 +',' from  学生专业表 t2
    where t2.学生ID=t1.ID group by 专业名称 for xml path('')
    )as [专业]
     from 学生表 t1
    这种么