Search code examples
sqlsql-serversumpivot

SQL SUM multiple Rows into a single Column


I have a list of data and that data repeats a lot, plainly down to the fees. There are two types of fees; TypeA and TypeB.

I currently have:

Person Value Type
John 10 TypeA
John 10 TypeA
John 20 TypeB
John 20 TypeB
Steve 15 TypeA
Steve 15 TypeA
Steve 25 TypeB
Steve 25 TypeB

What I want is:

Person TypeA TypeB
John 20 40
Steve 30 50

Edit: I'm using SQL Server


Solution

  • If there's literally only two types, you can easily do this with conditional aggregation:

    select
    person,
    sum (case when type = 'TYPEA' then value end) as typeA,
    sum (case when type = 'TypeB' then value end) as typeB
    from
    <table>
    group by
    person