I have a table like this
books |---------------------|------------------|------------------|------------------| | book | source | store_price | bookstore_price | |---------------------|------------------|------------------|------------------| | Batman | store | 10.5 | 9.5 | |---------------------|------------------|------------------|------------------| | Superman | bookstore | null | 9 | |---------------------|------------------|------------------|------------------|
I need to select books and sum prices and my query so far looks like this
SELECT
book,
SUM(
CASE
WHEN source = 'store' then store_price
WHEN source = 'bookstore' then bookstore_price
END
) AS price
FROM books
GROUP BY 1
;
Is it possible to somehow optimize SUM select for ex. select source||'_price' from books;?
Thank you in advance!
priceand then the columnsourceis enough to distinguish what kind of price you have.with t(book, source, store_price, bookstore_price) as (values('Batman'::text, 'store'::text, 10.5, 9.5), ('Superman', 'bookstore', null, 9)) select *, (to_jsonb(t)->(source||'_price'))::numeric from t;But it is really bad design IMO.