JIYIK CN >

Current Location:Home > Learning > DATABASE > MySQL >

Calculating Percentages in MySQL

Author:JIYIK Last Updated:2025/04/22 Views:

We will use one or more columns to calculate percentages in MySQL. There are different ways to do this, and for each method we will use an example table.


Calculate percentage using a column in MySQL

We have a table called sales where ID, RepresentativeName, and Sale are the column names. The following query can be used to create and populate the sales table to practice this tutorial.

Sample code:

# create a table
CREATE TABLE sales (
  ID INT NOT NULL,
  RepresentativeName VARCHAR(45) NOT NULL,
  Sale INT NOT NULL,
  PRIMARY KEY (ID));

# insert data
INSERT INTO sales (ID, RepresentativeName, Sale) VALUES
(1, 'John', 15),
(2, 'Mehvish', 15),
(3, 'Saira', 30);

# display sales table data
SELECT * FROM sales;

Output:

+----+--------------------+------+
| ID | RepresentativeName | Sale |
+----+--------------------+------+
|  1 | John               |   15 |
|  2 | Mehvish            |   15 |
|  3 | Saira              |   30 |
+----+--------------------+------+
3 rows in set (0.00 sec)

To find the percentage of Sale field, we can CROSS JOIN the SUM() function of Sale attribute with the original relation (table). See the following query to do this.

Sample code:

SELECT RepresentativeName, Sale,
round(((Sale * 100) / temp.SalesSum),2) AS Percentage
FROM sales
CROSS JOIN (SELECT SUM(Sale) AS SalesSum FROM sales) temp;

Output:

+--------------------+------+------------+
| RepresentativeName | Sale | Percentage |
+--------------------+------+------------+
| John               |   15 |      25.00 |
| Mehvish            |   15 |      25.00 |
| Saira              |   30 |      50.00 |
+--------------------+------+------------+
3 rows in set (0.00 sec)

Here, we use round()the method to get the result to two decimal places. If we focus on the query used to find the percentage, we can see that we are using a subquery after the CROSS JOIN keyword to find the sum of the Sale attribute.


Calculating percentages using two columns in MySQL

We create a table named tests with ID, GroupName, EmployeesCount and SurveysCount as column names where ID is the PRIMARY KEY. Use the following query to move with us throughout the tutorial.

Sample code:

# create a table
CREATE TABLE tests (
  ID INT NOT NULL,
  GroupName VARCHAR(45) NOT NULL,
  EmployeesCount INT NOT NULL,
  SurveysCount INT NOT NULL,
  PRIMARY KEY (ID));

# insert data
INSERT INTO tests (ID, GroupName, EmployeesCount, SurveysCount) VALUES
(1, 'Group A', '200', '10'),
(2, 'Group B', '300', '200'),
(3, 'Group C', '400', '300');

# display tests table data
SELECT * FROM tests;

Output:

+----+-----------+----------------+---------------+
| ID | GroupName | EmployeesCount | SurveysCount |
+----+-----------+----------------+---------------+
|  1 | Group A   |            200 |            10 |
|  2 | Group B   |            300 |           200 |
|  3 | Group C   |            400 |           300 |
+----+-----------+----------------+---------------+
3 rows in set (0.00 sec)

We use the following query to calculate the percentage using the EmployeesCount and SurveysCount fields.

Sample code:

SELECT GroupName, EmployeesCount, SurveysCount, COUNT( SurveysCount ) AS testA,
        concat(round(( SurveysCount/EmployeesCount * 100 ),2),'%') AS Percentage
FROM tests
GROUP BY EmployeesCount;

Output:

+-----------+----------------+--------------+-------+------------+
| GroupName | EmployeesCount | SurveysCount | testA | Percentage |
+-----------+----------------+--------------+-------+------------+
| Group A   |            200 |           10 |     1 | 5.00%      |
| Group B   |            300 |          200 |     1 | 66.67%     |
| Group C   |            400 |          300 |     1 | 75.00%     |
+-----------+----------------+--------------+-------+------------+
3 rows in set (0.00 sec)

We calculate the percentage by dividing SurveysCount by EmployeesCount and multiplying by 100. We use the round() function to round it to two decimal places to make it more readable.

Also, using concat()the function to concatenate it with the % symbol makes it easy to understand.


Calculating Percentages in MySQL Using the OVER() Function

OVER()The function is one of the window functions in MySQL and is used to calculate values ​​within a specific range of values. We can also use this function to calculate percentages.

OVER()Functions are very useful and can help us avoid subqueries to calculate percentages. Create a Products table with ProductID, ProductName, and SupplierID as attribute names to see this functionality.

Technically, SupplierID must be a foreign key, but we'll leave it as a simple field for demonstration purposes. Use the following queries to create the Products table and insert data.

Sample code:

CREATE TABLE products (
  ProductID INT NOT NULL,
  ProductName VARCHAR(45) NOT NULL,
  SupplierID INT NOT NULL,
  PRIMARY KEY (ProductID));

INSERT INTO products (ProductID, ProductName, SupplierID)
VALUES
(1,'Coca Cola', 2),
(2, 'Wavy Chips', 2),
(3, 'Dairy Milk Chocolate', 1),
(4, 'Parley Biscuits', 3),
(5, 'Knorr Nodles', 3),
(6, 'Snickers Chocolate', 3);

SELECT * FROM products;

Output:

+-----------+----------------------+------------+
| ProductID | ProductName          | SupplierID |
+-----------+----------------------+------------+
|         1 | Coca Cola            |          2 |
|         2 | Wavy Chips           |          2 |
|         3 | Dairy Milk Chocolate |          1 |
|         4 | Parley Biscuits      |          3 |
|         5 | Knorr Nodles         |          3 |
|         6 | Snickers Chocolate   |          3 |
+-----------+----------------------+------------+
6 rows in set (0.00 sec)

Now, use the following query to calculate the percentage of products provided by each supplier. We use OVER()the function instead of a subquery to get the sum of the products.

Sample code:

SELECT SupplierID AS Supplied_By, count(*) * 100.0 / sum(count(*)) Over() as 'Supplier Percentage'
FROM products
GROUP BY SupplierID;

Output:

+-------------+---------------------+
| Supplied_By | Supplier Percentage |
+-------------+---------------------+
|           2 |            33.33333 |
|           1 |            16.66667 |
|           3 |            50.00000 |
+-------------+---------------------+
3 rows in set (0.09 sec)

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Changing max_allowed_packet Size in MySQL Server

Publish Date:2025/04/22 Views:192 Category:MySQL

This article explains how to change the max_allowed_packet size in MySQL server. To understand this, we will use two operating systems, Windows 10 and Linux (Ubuntu). Changing max_allowed_packet Size in MySQL Server If we try to upload a fi

Zerofill usage, advantages and alternatives in MySQL

Publish Date:2025/04/22 Views:195 Category:MySQL

In this article we will understand the uses, advantages and alternatives of ZEROFILL attribute in MySQL. Use and benefits of the ZEROFILL attribute in MySQL The benefit of using the ZEROFILL attribute is that it has nothing to do with input

Compare only MySQL timestamp dates to date parameters

Publish Date:2025/04/22 Views:64 Category:MySQL

In this article we will use the DATE() , CAST() , and CONVERT() functions to compare MySQL timestamp dates with only the date parameter. DATE() vs. CAST() vs. CONVERT() in MySQL Below is a brief description of each function. You can also fi

Installing MySQL Client in Linux

Publish Date:2025/04/22 Views:186 Category:MySQL

MySQL is an abbreviation for Structured Query Language which is a relational database management system. It is an open source database which is freely available and used for both large and small applications. The use cases are in school app

Subtraction in MySQL

Publish Date:2025/04/21 Views:140 Category:MySQL

MINUS Operator is used in SQL to find unique elements in table A that are not present in table B. Through this tutorial, we will see how to emulate the operator in MySQL MINUS to get the desired result. We will understand it by using NOT IN

INTERSECT Operator in MySQL

Publish Date:2025/04/21 Views:99 Category:MySQL

This article will help you understand INTERSECT the operator. Although MySQL does not support INTERSECT and MINUS / EXCEPT , there are other ways to simulate this functionality. We will see INTERSECT what is , its benefits, and learn variou

Deleting using Join in MySQL

Publish Date:2025/04/21 Views:158 Category:MySQL

This tutorial article will show you how to use MySQL JOIN methods to delete data from multiple tables. This is useful when you are simultaneously deleting records from one table that are related to a specific record in another table. DELETE

MySQL using LIKE in case insensitive search

Publish Date:2025/04/21 Views:131 Category:MySQL

This tutorial article will show you how to use LIKE the operator to search a column. We will show you how to use it correctly to include all results that meet certain criteria, regardless of whether the value is uppercase or lowercase. LIKE

Loop PHP MySQLi Get Array Function

Publish Date:2025/04/21 Views:105 Category:MySQL

MySQLi fetch function is used to access data from the database server. After fetching the data, you can also iterate over it MySQLi with queries. In this article, we will see mysqli_fetch_array() the use of functions and methods to iterate

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial