Search code examples
sqlpercentage

Calculate percentage between two columns in SQL Query as another column


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?


Solution

  • 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