如何使用 SQL 计算 table 的频率百分比?
How to calculate frequency percentages for a table using SQL?
假设我有一些数据如下:
ID data fingers rating
001 hello y 0
002 hello n 0
003 bye n 0
004 hello y 1
005 bye n 0
我想要的只是一个 table 显示 data
中每个值的频率
结果如下:
data count pct
hello 3 .6
bye 2 .4
感觉很简单,但我很难在 Snowflake 中完成这项工作,有什么想法吗?
您可以使用条件聚合:
select data, count(*),
avg(case when fingers = 'y' then 1.0 else 0 end)
from t
group by data;
这里是你如何做到的:
select data , count(*) count, count(*) / sum(count(*)) over () pct
from table
group by data;
假设我有一些数据如下:
ID data fingers rating
001 hello y 0
002 hello n 0
003 bye n 0
004 hello y 1
005 bye n 0
我想要的只是一个 table 显示 data
结果如下:
data count pct
hello 3 .6
bye 2 .4
感觉很简单,但我很难在 Snowflake 中完成这项工作,有什么想法吗?
您可以使用条件聚合:
select data, count(*),
avg(case when fingers = 'y' then 1.0 else 0 end)
from t
group by data;
这里是你如何做到的:
select data , count(*) count, count(*) / sum(count(*)) over () pct
from table
group by data;