Multiple rows of same site with different managers for each - how to pivot

  • STRING_AGG() is your friend here, but the fact that it does not support DISTINCT (eg, to avoid John/John/David) complicates things somewhat. Here is one solution.

    DROP TABLE IF EXISTS #Sales;

    CREATE TABLE #Sales (Site VARCHAR(29), Manager VARCHAR(100), Sales INT, Items INT);

    INSERT #Sales (Site, Manager, Sales, Items)
    VALUES
    ('Leeds', 'John', 1000, 28)
    ,('Leeds', 'David', 2000, 32)
    ,('Leeds', 'John', 1599, 41)
    ,('Manchester', 'Andrew', 2000, 19);

    SELECT
    s.Site
    , AllManagers = calcs.AllManagers
    , Sales = SUM(s.Sales)
    , Items = SUM(s.Items)
    FROM #Sales s
    CROSS APPLY
    (
    SELECT AllManagers = STRING_AGG(a.Manager, '/') WITHIN GROUP(ORDER BY a.Manager)
    FROM
    (SELECT DISTINCT s1.Site, s1.Manager FROM #Sales s1) a
    WHERE a.Site = s.Site
    ) calcs
    GROUP BY s.Site
    , calcs.AllManagers;

  • Thanks Phil, I'll have a look at this.

    Cheers

    Andrew

     

  • Bingo! Works a treat.

    Many thanks

    Andrew

  • andrewjmdata wrote:

    Bingo! Works a treat.

    Many thanks

    Andrew

    Great! Thanks for posting back.


Viewing 4 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply