Skip to content

Instantly share code, notes, and snippets.

@ricardolsmendes
Last active September 24, 2022 22:43
Show Gist options
  • Save ricardolsmendes/0c3d4cf9c65e9e243a2e0b68b7d3dce6 to your computer and use it in GitHub Desktop.
Save ricardolsmendes/0c3d4cf9c65e9e243a2e0b68b7d3dce6 to your computer and use it in GitHub Desktop.
create or replace view finservam.prod.position (
symbol, exchange, date, trader, pm, num_shares_cumulative, cash_cumulative, close,
market_value, pnl comment 'Profit and Loss: Demonstrate comment on view column'
)
comment = 'what assets owned; demo Window Function running sum'
as
with cte as (
select t.symbol, exchange, t.date, trader, pm,
sum(num_shares) over(
partition by t.symbol, exchange, trader
order by t.date rows unbounded preceding
) num_shares_cumulative,
sum(cash) over(
partition by t.symbol, exchange, trader
order by t.date rows unbounded preceding
) cash_cumulative,
s.close
from finservam.prod.trade t
inner join finservam.prod.stock_history s
on t.symbol = s.symbol and s.date = t.date
)
select *, num_shares_cumulative * close as market_value,
num_shares_cumulative * close + cash_cumulative as pnl
from cte;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment