Search code examples
sqlpivotwhere-clausesumifs

Sum + Pivot + Where calculation in SQL


I'm new to SQL and tried searching for a post mappable to my own, but could not find one, so any advice would be really appreciated!

I have a dataset that looks like this (but ~25 million rows):

ID	Date	Amount	Type
112233	12/1/2018	300	3
112233	12/1/2018	80	3
112233	12/1/2018	60	0
112233	12/1/2018	40	3
112233	12/1/2018	20	3
112233	12/1/2018	40	3
112233	12/1/2018	0	0
112233	12/2/2018	120	3
112233	12/2/2018	120	3
112233	12/2/2018	120	0
112233	12/2/2018	120	3
112233	12/3/2018	120	3
112233	12/3/2018	120	0
112233	12/3/2018	120	0
112233	12/3/2018	120	3
112233	12/3/2018	120	3
112233	12/3/2018	120	3
112233	12/3/2018	120	3
666600	12/1/2018	0	0
666600	12/1/2018	0	0
666600	12/1/2018	100	3
666600	12/1/2018	400	3
666600	12/1/2018	80	3
666600	12/1/2018	40	3
666600	12/1/2018	0	0
666600	12/2/2018	80	3
666600	12/2/2018	0	0
666600	12/2/2018	80	3
666600	12/2/2018	0	0
666600	12/2/2018	500	0
666600	12/2/2018	100	3
666600	12/3/2018	400	3
666600	12/3/2018	80	3
666600	12/3/2018	40	3
666600	12/3/2018	0	0
666600	12/3/2018	80	3
666600	12/4/2018	0	0
666600	12/4/2018	80	3

and I need it to look like this:

ID	Amount	Type
112233	420	0
112233	1,440	3
666600	500	0
666600	1,560	3

In excel terms, what I want to do is: a SUMIFS function, summing 'Amount' by 'ID' (in this example 112233 and 666600) and by 'Type' (either 0 or 3).

Is this doable in SQL? Thanks!


Solution

  • You can try following solution:

    SELECT ID, Sum(Amount) as 'Amount', Type
    FROM tablename
    GROUP BY ID, Type;