CREATE MATERIALIZED VIEW alpheya_experience_bff.orders_mv AS
SELECT
id AS order_id,
etag,
client_order_id,
customer_relationship_id,
portfolio_id,
security_account_id,
asset_id,
side AS order_side,
workflow_state,
execution_state,
instruction,
execution_spec,
cost_estimate,
initiator,
filled_quantity,
created_at
FROM (
SELECT
id,
etag,
client_order_id,
customer_relationship_id,
portfolio_id,
security_account_id,
asset_id,
side,
workflow_state,
execution_state,
instruction,
execution_spec,
cost_estimate,
initiator,
filled_quantity,
created_at,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY created_at DESC) AS rn
FROM order_service.orders
) AS ranked_orders
WHERE
rn = 1