To โskipโ missing rows with NULL values โโin the resulting array, build your query in the full row grid and LEFT JOIN actual grid values. <w> Given this table definition:
CREATE TEMP TABLE price ( commodity text , value numeric , ts timestamp
I use generate_series() to get a list of timestamps representing years, and CROSS JOIN for a unique list of all products ( SELECT DISTINCT ... ).
SELECT commodity, (array_agg(value ORDER BY ts DESC)) AS years FROM generate_series ('2002-01-01 00:00:00'::timestamp , '2004-01-01 00:00:00'::timestamp , '1y') t(ts) CROSS JOIN (SELECT DISTINCT commodity FROM price) c(commodity) LEFT JOIN price p USING (ts, commodity) GROUP BY commodity;
Result:
COPPER {NULL,99.45,96.45} GOLD {150.45,140.45,130.45} MERCURY {60,NULL,NULL} SILVER {80.45,70.45,60.45}
SQL Fiddle
I drop the array into the text in the fiddle because the display sucks and swallows the NULL values โโotherwise.
Erwin Brandstetter Mar 18 '14 at 13:28 2014-03-18 13:28
source share