问题:一个表test,有2列:firstname varchar(50),domain varchar(50)。
test表有如下数据行:
firstname domain
----------------------
tony group1
tony group2
tony group3
john group4
提问:求一条sql,查询结果可以按如下格式显示:
firstname domain
---------------------------
tony group1,group2,group3
john group4
解决方法1
select [name],(select [group] from test where name=x.name for xml path('')) from test x group by [name]
解决方法2
通过函数的方式
参考例子
create function Sum_ByGroup(@DepartmentName varchar(50))
returns varchar(8000)
as
begin
declare @ret varchar(8000)
set @ret = ''
select @ret = @ret+','+EmpoyeeName from Employees where DepartmentName = @DepartmentName
set @ret = stuff(@ret,1,1,'')
return @ret
end
go
select DepartmentName,dbo.Sum_ByGroup(DepartmentName) as EmployeesList from Employees
group by DepartmentName
go
总结:对于group by的问题
思路一:for xml path
思路二:自定义函数
重在思考问题的方向