Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percentage between two columns in SQL Query as another column

Tags:

I have a table with two columns, number of maximum number of places (capacity) and number of places available (availablePlaces)

I want to calculate the availablePlaces as a percentage of the capacity.

availablePlaces    capacity 1                  20 5                  18 4                  15 

Desired Result:

availablePlaces    capacity  Percent 1                  20        5.0 5                  18        27.8 4                  15        26.7 

Any ideas of a SELECT SQL query that will allow me to do this?

like image 897
missdevops Avatar asked Apr 10 '16 15:04

missdevops


People also ask

How do I find the difference between two columns in SQL?

To calculate the difference between two dates in different columns, we use the two columns createdDate and LastLogin of the registration table and apply the DATEDIFF function on these columns. To find the difference between the two dates in different columns, we need two dates from the different columns.

How do you aggregate percentage in SQL?

Inline View in SELECT The idea here is to treat the total as a single number that we can directly use as the denominator in the division. 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.


1 Answers

Try this:

SELECT availablePlaces, capacity,         ROUND(availablePlaces * 100.0 / capacity, 1) AS Percent FROM mytable 

You have to multiply by 100.0 instead of 100, so as to avoid integer division. Also, you have to use ROUND to round to the first decimal digit.

Demo here

like image 124
Giorgos Betsos Avatar answered Sep 21 '22 23:09

Giorgos Betsos