SQL Server Table Calculations -
given:
+-----------+---------------+-------------+-------+ | name | item | year | value | +-----------+---------------+-------------+-------+ | company | sales | 2017 | 100 | | company | sales | 2016 | 100 | | company | sales | 2015 | 400 | | company | profit | 2017 | 50 | | company | profit | 2016 | 50 | | company | profit | 2015 | 200 | | company b | sales | 2017 | 200 | | company b | sales | 2016 | 100 | | company b | profit | 2017 | 20 | | company b | profit | 2016 | 20 | +-----------+---------------+-------------+-------+
how use sql transform 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 given year and
- 2 year ave: margin year + margin of previous year / 2,
null
if there no data previous year.
my approach first aggregate once on table using group by
compute profit margins each company in each year. then, make second pass using lag()
calculate recent 2 year margin average.
with cte ( select name, year, 100*max(case when item = 'profit' value end) / max(case when item = 'sales' value end) margins yourtable group name, year ) select name, year, margins, (margins + lag(margins) on (partition name order year)) / 2 [2 yr avg] cte order name, year
for second table output, can pivot result query. place code gave cte, , pivot on margin columns.
output:
demo here:
Comments
Post a Comment