AFP_555 AFP_555 - 1 year ago 71
SQL Question

SQL columns filtered diferently

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 querys, one for each year? If so, how can I join both results later?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download