-- Find the top 5 products whose revenue has decreased in comparison to the previous…
- User
-- Find the top 5 products whose revenue has decreased in comparison to the previous year (both 2022 and 2023). Return the product name, -- revenue for the previous year, revenue for the current year, revenue decreased, and the decreased ratio (percentage).
CREATE TABLE product_revenue (product_name VARCHAR(255), year INTEGER, revenue DECIMAL(10, 2)); INSERT INTO product_revenue (product_name, year, revenue) VALUES ('Product A', 2022, 10000.00), ('Product A', 2023, 9500.00), ('Product B', 2022, 15000.00), ('Product B', 2023, 14500.00), ('Product C', 2022, 8000.00), ('Product C', 2023, 8500.00), ('Product D', 2022, 12000.00), ('Product D', 2023, 12500.00), ('Product E', 2022, 20000.00), ('Product E', 2023, 19000.00), ('Product F', 2022, 7000.00), ('Product F', 2023, 7200.00), ('Product G', 2022, 18000.00), ('Product G', 2023, 17000.00), ('Product H', 2022, 3000.00), ('Product H', 2023, 3200.00), ('Product I', 2022, 9000.00), ('Product I', 2023, 9200.00), ('Product J', 2022, 6000.00), ('Product J', 2023, 5900.00);
- Assistant
To find the top 5 products whose revenue has decreased between 2022 and 2023 and display the required information, you can use the following SQL query:
WITH RevenueDifference AS ( SELECT pr2022.product_name, pr2022.revenue AS revenue_2022, pr2023.revenue AS revenue_2023, (pr2022.revenue - pr2023.revenue) AS revenue_decreased, ((pr2022.revenue - pr2023.revenue) / pr2022.revenue * 100) AS decreased_ratio FROM product_revenue pr2022 JOIN product_revenue pr2023 ON pr2022.product_name = pr2023.product_name WHERE pr2022.year = 2022 AND pr2023.year = 2023 AND pr2022.revenue > pr2023.revenue ) SELECT product_name, revenue_2022, revenue_2023, revenue_decreased, decreased_ratio FROM RevenueDifference ORDER BY revenue_decreased DESC LIMIT 5;