AFP_555 AFP_555 - 5 months ago 40
SQL Question

SQL columns filtered differently

It's been a while since I deal with SQL. Let's say I have a table Transaction with the following columns: Company, Year, Value.

I want to create a resultset that sums the total value for each Company, but in one column I want 2015 and in other 2016.

Company | Total 2015 | Total 2016 |

Sounds pretty basic but I haven't been able to figure it out.

Should I create two queries, one for each year? If so, how can I join both results later?


Here's one option using conditional aggregation:

select company, 
       sum(case when year = 2015 then value end) total2015,
       sum(case when year = 2016 then value end) total2016
from Transaction 
group by company