现在有表:
table1name        product
张三         盘子
张三         碗
张三         锅
李四         茶杯
李四         盘子得到如下结果张三       盘子,碗,锅
李四       茶杯,盘子查询sql 语句怎么写?

解决方案 »

  1.   

    if object_id('table1') is not null drop table table1
    create table table1
    (
     name varchar(20),
     product varchar(20)
    )
    insert into table1 select '张三','盘子'
    union all select '张三','碗'
    union all select '张三','锅'
    union all select '李四','茶杯'
    union all select '李四','盘子'
    create function dbo.FC_getstr(@name varchar(10))
    returns varchar(50)
    as
    begin
      declare @str varchar(100)
     set @str=''
      select @str=@str+','+product from table1 where name=@name
      return stuff(@str,1,1,'')
    endselect distinct name,dbo.FC_getstr(name) products from table1name                 products
    -------------------- --------------------------------------------------
    李四                   茶杯,盘子
    张三                   盘子,碗,锅(2 行受影响)
      

  2.   

    IF EXISTS (SELECT * FROM sysobjects WHERE NAME ='table1')
        DROP TABLE [table1]
    CREATE TABLE [table1]
    (
        [name]  varchar(100)  NULL ,
        [product]  varchar(100) NULL
    )
    GO--插入测试数据
    INSERT INTO [table1] ([name],[product])
        SELECT '张三','盘子' UNION
        SELECT '张三','碗' UNION
        SELECT '张三','锅' UNION
        SELECT '李四','茶杯' UNION
        SELECT '李四','盘子'
    GODROP FUNCTION f_t
    --
    create function f_t(@value VARCHAR(100))
    returns nvarchar(4000)
    as
    begin
    declare @s nvarchar(4000)
    set @s=''
    select @s=@s+','+product from table1 where name=@value
    return(stuff(@s,1,1,''))
    END
    GO--调用
    select [NAME],dbo.f_t([NAME])  from table1 group by [NAME]/*
    李四    茶杯,盘子
    张三    锅,盘子,碗
    */