# Alternative to Self Join

You can aggregate all uns/value pairs into a JSON object, then use that to access the UNS values by name. This requires some casting as the values can only be extracted as text from the JSON object, but the formula looks very similar to your description then:

with vals(postcode, v) as (
select postcode, json_object_agg(uns, value)
from x
group by postcode
), factors (postcode, denominator, divisor) as (
select postcode,
(v->>'53')::decimal * (v->>'56')::decimal + (v->>'54')::decimal * (v->>'57')::decimal + (v->>'55')::decimal * (v->>'58')::decimal,
(v->>'56')::decimal + (v->>'57')::decimal + (v->>'58')::decimal
from vals
)
select postcode,
denominator / nullif(divisor, 0)
from factors;


I have divided the aggregation, the evaluation of the denominator and divisor and the final division into three steps to make it more readable.

Online example: http://rextester.com/IZYT54566

You can simplify the formula by creating a function:

create function val(p_vals json, p_uns text)
returns decimal
as $$select (p_vals ->> p_uns)::decimal;$$
language sql;

with vals (postcode, v) as (
select postcode, json_object_agg(uns, value)
from x
group by postcode
), factors (postcode, denominator, divisor) as (
select postcode,
val(v, '53') * val(v, '56') + val(v, '54') * val(v, '57') + val(v, '55') * val(v, '58'),
val(v, '56') + val(v, '57') + val(v, '58')
from vals
)
select postcode,
denominator / nullif(divisor, 0)
from factors;


The PIVOT pattern would work for this. It converts rows' values to columns in a single row, according to their common key. There are a few ways to implement this. Some require only a single table scan.

After the PIVOT you would have a table with one row per postcode and a column per value. The remainder of the query would be written as though it referenced a single table.

Assuming that (postcode, uns) are UNIQUE (probably, a PK), probably the simplest way, probably the most portable one, although probably not the optimal: use as many subselects as needed:

SELECT
postcode,
((SELECT value FROM t WHERE t.uns = 53 AND t.postcode = p.postcode) *
(SELECT value FROM t WHERE t.uns = 56 AND t.postcode = p.postcode) +
(SELECT value FROM t WHERE t.uns = 54 AND t.postcode = p.postcode) *
(SELECT value FROM t WHERE t.uns = 57 AND t.postcode = p.postcode) +
(SELECT value FROM t WHERE t.uns = 55 AND t.postcode = p.postcode) *
(SELECT value FROM t WHERE t.uns = 58 AND t.postcode = p.postcode)
)::double precision /
nullif( (SELECT sum(value) FROM t
WHERE t.uns IN (56, 57, 58) AND t.postcode = p.postcode), 0)
AS formula
FROM
(SELECT DISTINCT postcode FROM t) AS p
ORDER BY
postcode ;


Check at SQLFiddle.