AdBlock Detected!
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.
SQL Percent To Total |
|
SQL > Advanced SQL >
Percent To Total
To calculate percent to total in SQL, we need to first calculate the total, and then we divide each individual value by the total to find the percentage. So this is a two-step process. There are multiple ways to accomplish this. Here we will show three different ways: Calculating percent to total in SQL requires dividing each row's value by the overall sum — achievable via an inline subquery, a derived table in FROM, or a CTE for cleaner, reusable logic.
Inline View in SELECTThe first method is to use the inline view construct in the SELECT statement. The idea here is to treat the total as a single number that we can directly use as the denominator in the division. Let's use an example to illustrate. Say we have the following table, Table Total_Sales
we would type, Result:
The inline view SELECT SUM(Sales) FROM Total_Sales calculates the sum. We can then divide the individual values by this sum to obtain the percent to total for each row. We include * 1.0 because in some databases (such as SQLite), dividing an integer by another integer results in an integer, which is not what we want. Multiplying the numerator by 1.0 forces the expression to be considered as a float by the database, and the result of the division will have the float data type, which is what we want. Inline View in FROMThe second method is to the inline view in the FROM statement. Here, the inline view essentially becomes another table that you can query from. Note that here we do not need to specify the join condition between the two tables, as the inline view only has a single column and a single row. In this case, the SQL would become as follows: Using Common Table Expression (CTE)A third way to calculate percent to total is to use the Common Table Expression (CTE). In this case, we will first use the WITH statement to calculate the total, and then use the result in the main query to calculate the percent to total. In our example, the SQL would look like the following: List of SQL Complex Operations
Frequently Asked Questions
|
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.