如何获取 SQL 列中特定值的百分比?
How to get percentage of certain value in column with SQL?
我有一个 table:
id value
a1. 7
a2. 89
a3. None
a4. None
我想获得列值中 None 个值的百分比。 I don't need percentages of other values in that column, only None values.
怎么做?
select sum(value='None')*100/count(*) from a_table
我建议 avg()
:
select avg(case when value = 'none' then 1.0 else 0 end) as none_ratio
from t
您可以使用 count_if
:
WITH dataset(id,value) AS ( VALUES ('a1.','7'), ('a2.','89'), ('a3.','None'), ('a4.','None') )
SELECT count_if(value = 'None') * 1.0/count(*)
FROM dataset
输出:
_col0
0.5
我有一个 table:
id value
a1. 7
a2. 89
a3. None
a4. None
我想获得列值中 None 个值的百分比。 I don't need percentages of other values in that column, only None values.
怎么做?
select sum(value='None')*100/count(*) from a_table
我建议 avg()
:
select avg(case when value = 'none' then 1.0 else 0 end) as none_ratio
from t
您可以使用 count_if
:
WITH dataset(id,value) AS ( VALUES ('a1.','7'), ('a2.','89'), ('a3.','None'), ('a4.','None') )
SELECT count_if(value = 'None') * 1.0/count(*)
FROM dataset
输出:
_col0 |
---|
0.5 |