I have a table market_trades with columns timestamp, market_id, and amount:
api_production=# \d market_trades;
Table "public.market_trades"
Column | Type | Modifiers
----------------+-----------------------------+------------------------------------------------------------
id | integer | not null default nextval('market_trades_id_seq'::regclass)
market_id | integer | not null
timestamp | timestamp without time zone | not null
amount | numeric(16,8) | not null
And I just created a table market_trades_sum_cache:
api_production=# \d market_trades_sum_cache;
Table "public.market_trades_sum_cache"
Column | Type | Modifiers
----------------+-----------------------------+------------------------------------------------------------
id | integer | not null default nextval('market_trades_sum_cache_id_seq'::regclass)
market_id | integer | not null
start_time | timestamp without time zone | not null
end_time | timestamp without time zone | not null
sum | numeric(16,8) | not null
I want to write a view (or some other type of reusable function) called trade_volume that takes a market_id, start_time, and end_time as parameters and does the following:
- If there is a row in
market_trades_sum_cachewith the givenmarket_id,start_time, andend_time, return the correspondingsum. - Otherwise, add up the
amounts of all rows inmarket_tradeswith the givenmarket_idand whosetimestampis betweenstart_timeandend_time, store that sum as a new row inmarket_trades_sum_cache, and return the sum.
Is this possible in PostgreSQL 9.3?
BONUS: Use PostgreSQL's timestamp range types (tsrange in PostgreSQL 9.2+) instead of start_time and end_time in market_trades_sum_cache.