[英]SQL divide 2 columns
I need to calculate population density in SQL. 我需要在SQL中计算人口密度。 I have a column with population and a column with area but I'm can't figure out how to execute it, I get a division by zero error. 我有一列人口,一列面积,但我不知道如何执行它,我得到除以零误差。
Here is what I tried: 这是我尝试过的:
select name, population, gdp, area, [population]/[area] as pop_density
from country
group by name
order by gdp;
Why do you need group by
? 为什么需要group by
?
There is no need for grouping. 无需分组。
Even if you did need group by
you couldn't select non aggregated columns like: 即使您确实需要group by
,也无法选择非聚合列,例如:
population, gdp, area
. population, gdp, area
。
Just check for null
or 0
for the column area
: 只需检查null
或0
的列area
:
select
name, population, gdp, area,
case coalesce(area, 0)
when 0 then null
else population / area
end as pop_density
from country
order by gdp
Use nullif()
: 使用nullif()
:
select name, population, gdp, area,
population / nullif(area, 0) as pop_density
from country
order by gdp;
The group by
doesn't seem necessary. group by
似乎没有必要。
nullif()
is a standard function that returns NULL
when the two values passed in are equal. nullif()
是一个标准函数,当传入的两个值相等时会返回NULL
。 If your database does not support it, you can do the same thing with a case
expression. 如果您的数据库不支持它,则可以使用case
表达式执行相同的操作。
Just add in where clause as
只需在where clause as
添加where clause as
select name, population, gdp, area,
[population]/[area] as pop_density
from country where area
NOT IN (NULL,0) group by name
order by gdp
Or, You can handle your divisor area's value 0 via Case
Statements... 或者,您可以通过Case
Statements处理除数区域的值0。
.......Case when Area IN (Null,0)
then 0
else
[population]/[area]
select name, population, gdp, area, [population]/[area] as pop_density
from country
where area is not null and area is not 0
group by name
order by gdp;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.