Flatten association table to multi-value column?

后端 未结 4 1124
旧时难觅i
旧时难觅i 2021-01-07 07:48

I have a table with just product ID\'s and category ID\'s (products can be in more than one category). How can I flatten the category ID\'s into a product column so I end us

4条回答
  •  梦毁少年i
    2021-01-07 08:21

    I would suggest using a Recursive CTE. I believe that it would be something like this:

    select productid, categoryid, 
        row_number() over (partition by id order by categoryid) as rownum
    into #tabletorecurse
    from TABLENAME
    
    with finaloutput as
    (
        select productid as id, name, desc, categoryid as categories, rownum
        from #tabletorecurse
            join PRODUCTTABLE
                on PRODUCTTABLE.id = #tabletorecurse.productid
        where rownum = 1
    
        union all
    
        select tr.id, tr.name, tr.desc, 
            finaloutput.categories + ', ' + tr.categoryid, tr.rownum
        from #tabletorecurse as tr
            join finaloutput 
                on finaloutput.rownum + 1 = tr.rownum 
                    and finaloutput.id = tr.productid
    )
    select id, name, desc, categories
    from finaloutput
        join 
        (
            select max(rownum) as maxrow, id
            from finaloutput
            group by id 
        ) as maxvalues
           on maxvalues.id = finaloutput.id 
               and maxvalues.maxrow = finaloutput.rownum
    

提交回复
热议问题