现有表A ID Name Units
--------------
1  aaa  a1
2  aaa  a2
3  aaa  a3
4  bbb  b1
5  bbb  b2
6  ccc  c1
7  ccc  c2
8  ddd  d1
9  ddd  c1需要得到如下结果:Name Units
--------------
aaa  a1, a2, a3
bbb  b1, b2
ccc  c1, c2
ddd  d1, c1请问查询语句该怎么写???

解决方案 »

  1.   

    create function F_Test(@Name nvarchar(20))
    returns nvarchar(1000)
    as
    begin
    declare @s nvarchar(1000)
    select @s=isnull(@s+',','')+Units from A where Name=@Name order by ID
    return@s
    end
      

  2.   

    忘了这当时是哪个写的了,
    反正不是我写的,贴过来参考!--> 1、表示地图上一条公路路线的表
    if object_id('A') is not null drop table A
    go
    create table A (linId int,port varchar(4))
    go
    insert into A
    select 1,'济南' union all
    select 1,'聊城' union all
    select 1,'....' union all
    select 1,'上海' union all
    select 2,'济南' union all
    select 2,'淄博' union all
    select 2,'青岛' union all
    select 3,'....'
    go-->2005
    select linId, roads=(stuff((select ','+port as [text()] from A where linId=t.linId for xml path('')),1,1,'')) from A as t group by linId
    /*
    linId       roads
    ----------- -------------------
    1           济南,聊城,....,上海
    2           济南,淄博,青岛
    3           ....
    */
    go--2000
    if object_id('fn_coalition') is not null drop function fn_coalition
    go
    create function fn_coalition(@linId int)
    returns varchar(1000)
    as
    begin
    declare @r varchar(1000)
    select @r=isnull(@r+',','')+port from A where linId=@linId
    return(@r)
    end
    goselect linId,dbo.fn_coalition(linId) from A group by linId
    /*
    linId       roads
    ----------- -------------------
    1           济南,聊城,....,上海
    2           济南,淄博,青岛
    3           ....
    */if object_id('A') is not null drop table A
    if object_id('fn_coalition') is not null drop function fn_coalition
      

  3.   

    select distinct Name,dbo.F_Test(Name) as Units from A
    DECLARE @t TABLE(id int, value varchar(10))INSERT @t SELECT 1, 'aa'UNION ALL SELECT 1, 'bb'UNION ALL SELECT 2, 'aaa'UNION ALL SELECT 2, 'bbb'UNION ALL SELECT 2, 'ccc' -- 查询处理SELECT *FROM(    SELECT DISTINCT         id    FROM @t)AOUTER APPLY(    SELECT         [values]= STUFF(REPLACE(REPLACE(            (                SELECT value FROM @t N                WHERE id = A.id                FOR XML AUTO            ), '<N value="', ','), '"/>', ''), 1, 1, ''))N
      

  4.   

    上面那个是小楼写的~
    http://topic.csdn.net/u/20080503/09/e9a46529-074f-47ac-aa5b-96ed720bf69c.html