两个表
A表,类别 , 品名
     A,
     B,
     C,B表,类别,品名,
     A,钢笔
     A,铅笔
     A,毛笔
     B,
     B,
现在要把B表的内容合并到A表,A表中A行的品名为,“钢笔,铅笔,毛笔”中间用逗号分隔!

解决方案 »

  1.   

    猜测lz的意思如下
    use tempdb;
    /*
    create table A
    (
    类别 nvarchar(10) not null,
    品名 nvarchar(10)
    );
    insert into A(类别,品名)
    values
    ('A',null),('B',null),('C',null);create table B
    (
    类别 nvarchar(10) not null,
    品名 nvarchar(10) not null
    );
    insert into B(类别,品名)
    values
    ('A','钢笔'),
    ('A','铅笔'),
    ('A','毛笔');
    */
    select A.类别,t.品名
    from A
    left join
    (
    select 类别, stuff((select ','+[品名] from B as t where 类别 = B.类别 for xml path('')), 1, 1, '') as [品名]
    from B
    group by B.类别
    ) as t on A.类别 = t.类别;
      

  2.   

    create table tb(类别 varchar(10),品名 nvarchar(10))
    insert into tb select 'A','钢笔'
    insert into tb select 'A','铅笔'
    insert into tb select 'A','毛笔'
    insert into tb select 'B','红墨水'
    insert into tb select 'B','蓝墨水'
    go
    select 类别,stuff((select ','+品名 from tb where 类别=a.类别 for xml path('')),1,1,'')品名 from tb a group by 类别
    go
    drop table tb
    /*
    类别         品名
    ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    A          钢笔,铅笔,毛笔
    B          红墨水,蓝墨水(2 行受影响)
    */
      

  3.   

    create table tb(类别 varchar(10),品名 nvarchar(10))
    insert into tb select 'A','钢笔'
    insert into tb select 'A','铅笔'
    insert into tb select 'A','毛笔'
    insert into tb select 'B','红墨水'
    insert into tb select 'B','蓝墨水'
    create table tb2(类别 varchar(10),品名 nvarchar(20))
    insert into tb2(类别) select 'A' union all select 'B'
    go
    /*
    --如果原表中没有数据,则
    insert into tb2
    select 类别,stuff((select ','+品名 from tb where 类别=a.类别 for xml path('')),1,1,'')品名 from tb a group by 类别
    */
    --如果原表有数据, 要更新,则:
    update tb2 set 品名=b.品名 from tb2 a inner join(
    select 类别,stuff((select ','+品名 from tb where 类别=a.类别 for xml path('')),1,1,'')品名 from tb a group by 类别
    )b on a.类别=b.类别select * from tb2
    /*
    类别         品名
    ---------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    A          钢笔,铅笔,毛笔
    B          红墨水,蓝墨水(2 行受影响)
    */go
    drop table tb,tb2