SQL, questions about join

前端 未结 3 1757
长发绾君心
长发绾君心 2021-01-23 04:48

I have two tables in sql 2012: name and prod with structure:

name: id int increment, name1 nvarchar(50)

prod:

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-23 04:53

    unfortunately, there's no easy way to do it in SQL Server. Known solutions are:

    • xml trick (see below);
    • using variable to accumulate data (don't work for multiple group rows, only with cursor);
    • custom CLR aggregate;

    here's xml:

    select
        n.name1,
        stuff(
            (
             select ', ' + p.product
             from prod as p
             where p.id_name = n.id
             for xml path(''),  type).value('.', 'nvarchar(max)')
        , 1, 2, '') as products
    from name as n
    

    sql fiddle demo

    here's variable:

    declare @product nvarchar(max), @id int
    
    select @id = 1
    
    select @product = isnull(@product + ', ', '') + product
    from prod
    where id_name = @id
    
    select name1, @product as products
    from name 
    where id = @id
    

    sql fiddle demo

提交回复
热议问题