postgresql - Postgres: How to get next item in an enum set? -
consider using code below. type enum_buysell
includes 2 values: buy
, sell
. need opposite value in cases, code looks ugly, imho. there way optimise it? thought of not using enum @ all, e.g. make boolean instead, idea's not perfect makes data less obvious.
select datetime, case when account_id_active = p_account_id , direction = 'buy' 'buy'::enum_buysell when account_id_active = p_account_id , direction = 'sell' 'sell'::enum_buysell when account_id_passive = p_account_id , direction = 'buy' 'sell'::enum_buysell when account_id_passive = p_account_id , direction = 'sell' 'buy'::enum_buysell end direction, price, volume deals account_id_active = p_account_id or account_id_passive = p_account_id order datetime desc limit 10;
since there's no function getting next value of enum in postgresql, should define yourself.
create function next_buysell (e enum_buysell) returns enum_buysell $$ begin return (case when e='buy'::enum_buysell 'sell'::enum_buysell else 'buy'::enum_buysell end); end $$ language plpgsql;
now, can use this:
postgres=# select next_buysell('sell'::enum_buysell); next_buysell -------------- buy (1 row) postgres=# select next_buysell('buy'::enum_buysell); next_buysell -------------- sell (1 row)
and case
statement becomes:
case when account_id_active = p_account_id direction when account_id_passive = p_account_id next_buysell(direction) end direction
Comments
Post a Comment