In this scenario, we will create SQL views to assist in managing and analyzing a financial portfolio. The portfolio management system includes several tables: investors, accounts, transactions, assets, and asset_prices. The goal is to create SQL views that provide insights into portfolio performance, asset allocation, and investor activity.
investor_id (INT, Primary Key)name (VARCHAR)email (VARCHAR)created_at (TIMESTAMP)account_id (INT, Primary Key)investor_id (INT, Foreign Key)account_type (VARCHAR)created_at (TIMESTAMP)transaction_id (INT, Primary Key)account_id (INT, Foreign Key)asset_id (INT, Foreign Key)transaction_date (TIMESTAMP)transaction_type (VARCHAR)quantity (DECIMAL)price (DECIMAL)asset_id (INT, Primary Key)name (VARCHAR)asset_type (VARCHAR)asset_id (INT, Foreign Key)price_date (DATE)price (DECIMAL)This view calculates the current value of each investor’s portfolio based on the latest asset prices.
CREATE VIEW portfolio_performance AS
SELECT
i.investor_id,
i.name AS investor_name,
a.account_id,
SUM(t.quantity * ap.price) AS portfolio_value
FROM
investors i
JOIN
accounts a ON i.investor_id = a.investor_id
JOIN
transactions t ON a.account_id = t.account_id
JOIN
(SELECT asset_id, price
FROM asset_prices
WHERE price_date = (SELECT MAX(price_date) FROM asset_prices)) ap ON t.asset_id = ap.asset_id
GROUP BY
i.investor_id, i.name, a.account_id;
This view provides a breakdown of the portfolio by asset type for each investor.
CREATE VIEW asset_allocation AS
SELECT
i.investor_id,
i.name AS investor_name,
ass.asset_type,
SUM(t.quantity * ap.price) AS total_value
FROM
investors i
JOIN
accounts a ON i.investor_id = a.investor_id
JOIN
transactions t ON a.account_id = t.account_id
JOIN
assets ass ON t.asset_id = ass.asset_id
JOIN
(SELECT asset_id, price
FROM asset_prices
WHERE price_date = (SELECT MAX(price_date) FROM asset_prices)) ap ON t.asset_id = ap.asset_id
GROUP BY
i.investor_id, i.name, ass.asset_type;
This view tracks the activity of each investor, including the number of transactions and the total volume traded.
CREATE VIEW investor_activity AS
SELECT
i.investor_id,
i.name AS investor_name,
COUNT(t.transaction_id) AS total_transactions,
SUM(t.quantity * t.price) AS total_volume
FROM
investors i
JOIN
accounts a ON i.investor_id = a.investor_id
JOIN
transactions t ON a.account_id = t.account_id
GROUP BY
i.investor_id, i.name;
This view provides the historical price trends of each asset for analysis and reporting.
CREATE VIEW asset_price_trends AS
SELECT
a.asset_id,
a.name AS asset_name,
ap.price_date,
ap.price
FROM
assets a
JOIN
asset_prices ap ON a.asset_id = ap.asset_id
ORDER BY
a.asset_id, ap.price_date;
These views can now be used to generate reports or integrated into financial analysis tools to provide real-time insights into the portfolio’s performance. For example: