Given:
+-----------+---------------+-------------+-------+
| Name | Item | Year | Value |
+-----------+---------------+-------------+-------+
| Company A | Sales | 2017 | 100 |
| Company A | Sales | 2016 | 100 |
| Company A | Sales | 2015 | 400 |
| Company A | Profit | 2017 | 50 |
| Company A | Profit | 2016 | 50 |
| Company A | Profit | 2015 | 200 |
| Company B | Sales | 2017 | 200 |
| Company B | Sales | 2016 | 100 |
| Company B | Profit | 2017 | 20 |
| Company B | Profit | 2016 | 20 |
+-----------+---------------+-------------+-------+
How do I use SQL to transform it to:
+----------+---------------+--------+-----------+
| Name | Year | Margins| 2 yr Ave |
+----------+---------------+--------+-----------+
| CompanyA | 2015 | 50% | NULL |
| CompanyA | 2016 | 50% | 50% |
| CompanyA | 2017 | 50% | 50% |
| CompanyB | 2016 | 20% | NULL |
| CompanyB | 2017 | 10% | 15% |
+----------+---------------+--------+-----------+
and
+----------+---------------+--------+-----------+
| Name | Year | CompA | CompB |
+----------+---------------+--------+-----------+
| Margin | 2015 | 50% | NULL |
| Margin | 2016 | 50% | 20% |
| Margin | 2017 | 50% | 10% |
| 2Yr Ave | 2015 | NULL | NULL |
| 2Yr Ave | 2016 | 50% | NULL |
| 2Yr Ave | 2017 | 50% | 15% |
+----------+---------------+--------+-----------+
- Margin: (profit/sales*100) of a given year and
- 2 Year Ave: Margin this year + Margin of previous year / 2,
NULL
if there is no data for previous year.