SQL, questions about join

前端 未结 3 1756
长发绾君心
长发绾君心 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

    0 讨论(0)
  • 2021-01-23 04:57

    sqlfiddle

    select
    n.nameid [id],
    n.name [name],
    count(*)[count],
        stuff(
            (
             select ', ' + p.prod
             from prodtbl as p
             where p.nameid = n.nameid
             for xml path(''),  type).value('.', 'nvarchar(max)'), 1, 1, '') as products
    from nametbl n, prodtbl p
    where p.nameid = n.nameid
    group by n.nameid, n.name
    order by [id];
    

    enter image description here

    0 讨论(0)
  • 2021-01-23 05:14

    try this:

    SELECT
    G.id,
    G.name1,
    stuff(
        (select cast(',' as varchar(10)) + U.product
        from prod U
        WHERE U.id_name = G.id
        order by U.product
        for xml path('')
    ), 1, 1, '') AS prod
    FROM name G
    ORDER BY G.name1 ASC
    
    0 讨论(0)
提交回复
热议问题