I have to run a few calculations in my select query to get dynamic values for something like profit received on a sold inventory item. The formula goes (price minus discounts) - (total expenses) = profit
My query works fine but I have a lot of lines like this so it's completely unreadable for anyone else. Is there a way to assign variables or something to my various aggregate functions or casts?
Here's a simpler version of my query:
select
...
(sum(cast(ti.price as integer)) - sum(floor(cast(ti.discount as float)))) - sum(cast("exp".price as integer))) as profit,
...
from inventory as inv
left join transaction_item as ti on ti.inventory_id = inv.id
left join expense as exp on exp.inventory_id = inv.id
...
where
...
group by inv.id
For context:
tiis atransaction_itemtable (priceanddiscountare text columns)invis an inventory items tableexpis an expenses table (priceis a text column)
What I'd like to do instead of that long function chain:
((price_total - total_discounts) - total_expenses) as profit
...Where I define each of those variables somewhere. Is this possible or do I need to just accept that this query will be messy?
CREATEstatements of the tables (paste the text, don't use images),INSERTstatements for sample data (dito) and the desired result with that sample data in tabular text format.