Introduction
We use percent of total to see how much each part contributes to the whole in a simple way.
SELECT column1, column2, value_column, 100.0 * value_column / SUM(value_column) OVER () AS percent_of_total FROM table_name;
SELECT product_name, sales, 100.0 * sales / SUM(sales) OVER () AS percent_of_total FROM sales_data;
SELECT department, expense, 100.0 * expense / SUM(expense) OVER () AS percent_of_total FROM expenses;
CREATE TABLE sales_data ( product_name VARCHAR(20), sales INT ); INSERT INTO sales_data VALUES ('Apples', 50), ('Bananas', 30), ('Cherries', 20); SELECT product_name, sales, ROUND(100.0 * sales / SUM(sales) OVER (), 2) AS percent_of_total FROM sales_data ORDER BY product_name;
SUM(column) OVER () compute in a query?SUM(column) OVER () means sum over all rows without partitioning or grouping.SUM(sales) OVER () to get total sales across all rows, then divides each sales value by this total.sales_data with columns product and amount, what is the output of this query?SELECT product, amount, ROUND((amount / SUM(amount) OVER ()) * 100, 1) AS percent_total FROM sales_data ORDER BY product;
product | amount
-------|-------
A | 50
B | 30
C | 20SELECT product, sales, (sales / SUM(sales)) * 100 AS percent_total FROM sales_table;
orders with columns category and amount. Write a query to show each category, total amount per category, and percent of total amount across all categories. Which query is correct?SUM(amount) GROUP BY category to get total per category.SUM(SUM(amount)) OVER () to get grand total across all categories, then divide category total by this and multiply by 100.Pass the test and this pattern moves unknown