Let's suppose there's a table like this:
---------------------------------------------------------------------
| id | val_1 | val_2 | ... | val_n | attr_1 | attr_2 | ... | attr_n |
---------------------------------------------------------------------
val_i : DOUBLE PRECISION
attr_i : INTEGER
I need to get every AVG( "val_i" )
where "attr_i"
equals some value (the same for every "attr"
). If there's no matches for some "attr_i"
then AVG( "val_i" )
should be NULL
, e.g.:
---------------------------------------
| val_1 | val_2 | val_3 | ... | val_n |
---------------------------------------
| NULL | 1.5 | NULL | ... | 12.74 |
---------------------------------------
The following SQL seems to work as expected:
SELECT
AVG( t1."val_1" ),
AVG( t2."val_2" ),
...
AVG( tn."val_n" )
FROM "test" t1
FULL OUTER JOIN "test" t2 ON ( t2."attr_2" = t1."attr_1")
FULL OUTER JOIN "test" t3 ON ( t3."attr_3" = t1."attr_1")
...
FULL OUTER JOIN "test" tn ON ( tn."attr_n" = t1."attr_1")
WHERE
( t1."attr_1" = some_value )
OR ( t2."attr_2" = some_value )
...
OR ( tn."attr_n" = some_value )
;
But it's too slow. For i == 4
and record count == 100
I had to interrupt operation after ~40 min.
So is there a faster way? The best would be to have single SQL (not a stored procedure) returning single row. It should take a few seconds maximum for i == 6
and record count > 1000
.