Summarize data in cross-tab format

  • Thanks to anyone who can help. My assumption is that column #test.Type will only be 2 values, A or B.

    CREATE TABLE #test

    (

    Account int,

    Type char(1),

    Amount int

    )

    INSERT INTO #test

    SELECT 1,'A',4

    UNION

    SELECT 1,'B',2

    UNION

    SELECT 1,'A',5

    UNION

    SELECT 2,'B',5

    UNION

    SELECT 2,'B',8

    UNION

    SELECT 2,'A',1

    SELECT * FROM #test

    DROP TABLE #test

    --Desired results

    --First line is header

    Account,TypeA,TypeB

    1,9,2

    2,1,13

  • Not too hard, here is the code I came up:

    select

    Account,

    sum(case when Type = 'A' then Amount else 0 end) as TypeA,

    sum(case when Type = 'B' then Amount else 0 end) as TypeB

    from

    #test

    group by

    Account;

  • Perfect thanks. 🙂

Viewing 3 posts - 1 through 2 (of 2 total)

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