- create table tb ([id] int,[name] varchar(2))
- insert into tb
- select 1,'aa' union all
- select 2,'bb' union all
- select 1,'cc' union all
- select 3,'dd' union all
- select 2,'ee'
- select * from tb
- --查询
- select
- id,
- name=stuff((select ','+name from tb where id=t.id for xml path('')),1,1,'')
- from
- tb t
- group by
- id
- 方法二:
- CREATE FUNCTION GET_STRING(@ID INT)
- RETURNS VARCHAR(50)
- AS
- BEGIN
- DECLARE @NAME VARCHAR(500)
- SELECT @NAME=ISNULL(@NAME+',','')+NAME FROM TB WHERE ID=@ID
- RETURN @NAME
- END
- SELECT ID ,DBO.GET_STRING(ID)NAME FROM TB GROUP BY ID
- -----------------------------------------------------------------------
- 在oracle中,是有相对应的函数,sys_connect_by_path函数。
- 先在这里把oracle的函数实现也写下吧
- select id
- ,itrim(max(sys_connect_by_path(name,','))) as name
- from
- (select id
- ,name
- ,lead(rnFirst) over(partition by no order by rnFirst)rnNext
- from
- (select a.id
- ,a.name
- ,row_number() over(order by a.id,a.name desc) rnFirst
- from @t a) tmpTable1
- ) tmpTable2
- start with rnNext is null
- connect by rnNext = PRior rnFirst
- group by id
- 以上是实现oracle中的行转列方式。
- ********************************************下面我们来看一下sqlserver的,因为sqlserver没提供类似的函数,不知道sqlserver2012提供没
- 不过sqlserver支持起来也很简单,使用cross apply和for xml path组合来用,这两个单独都知道是怎么回事,怎么使用,但是真不知道还有它俩组合来完成这个功能的,感到很是不可思议,这里要感谢下网络上的人,原来自己写东西都是把所学到的知识记录到本机,从不放到网上,也可能是最近吧,好多工作不会,都是通过网络帮助,就把我所知道的东西也都放到网上来,大家一起学习。
- sqlserver:
- select id, SUBSTRING(names, 1, len(names)-1) from @t AS A cross APPLY
- (SELECT NAME + ',' FROM @t AS B WHERE A.id = B.id FOR XML PATH('')) D (names)
- GROUP BY id, names