将 SQL Query 中两列之间的百分比计算为另一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36531361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate Percentage between two columns in SQL Query as another column
提问by missdevops
I have a table with two columns, number of maximum number of places (capacity) and number of places available (availablePlaces)
我有一个包含两列的表格,最大位置数(容量)和可用位置数(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?
允许我这样做的 SELECT SQL 查询的任何想法?
Thanks!
谢谢!
回答by Giorgos Betsos
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.
您必须乘以 100.0 而不是 100,以避免整数除法。此外,您必须使用ROUND
舍入到第一个十进制数字。
回答by bryanblackbee
The following SQL query will do this for you:
以下 SQL 查询将为您执行此操作:
SELECT availablePlaces, capacity, (availablePlaces/capacity) as Percent
from table_name;