Return the percentage change of daily stock prices
-- Return the percentage change of daily stock prices compared to the first stock price of the month for each stock.
stock_id INT,
stock_name VARCHAR(50),
stock_price DECIMAL(10, 2),
trade_date DATE
);
INSERT INTO DailyStockPrices (stock_id, stock_name, stock_price, trade_date) VALUES
(1, 'Stock A', 100, '2024-01-01'),
(1, 'Stock A', 105, '2024-01-02'),
(1, 'Stock A', 110, '2024-01-03'),
(2, 'Stock B', 200, '2024-01-01'),
(2, 'Stock B', 190, '2024-01-02'),
(2, 'Stock B', 195, '2024-01-03');
SELECT
stock_id,
stock_name,
trade_date,
stock_price,
ROUND(((stock_price / first_month_price) - 1) * 100, 2) AS percent_change
FROM (
SELECT
stock_id,
stock_name,
trade_date,
stock_price,
FIRST_VALUE(stock_price) OVER (
PARTITION BY stock_id, EXTRACT(YEAR_MONTH FROM trade_date)
ORDER BY trade_date
) AS first_month_price
FROM DailyStockPrices
) AS stock_data
ORDER BY stock_id, trade_date;