用sql计算比率
我正在使用Hiveql查询预处理一些原始数据。在这个场景中,我有一张名为cloth的桌子,我有3种颜色的布料,分别是红色、蓝色和绿色。现在的问题是如何使用查询计算每种颜色的比率?用sql计算比率,sql,postgresql,bigdata,hiveql,Sql,Postgresql,Bigdata,Hiveql,我正在使用Hiveql查询预处理一些原始数据。在这个场景中,我有一张名为cloth的桌子,我有3种颜色的布料,分别是红色、蓝色和绿色。现在的问题是如何使用查询计算每种颜色的比率? 感谢您的帮助 正如您所说,您有一个名为cloth的表,其中包含3种cloth和3种color。 select cloth, avg(Case when color='red' then 1 else 0 end)/ Count(*) * 1.0 As redratio, avg(Case when color='blu
感谢您的帮助 正如您所说,您有一个名为
cloth
的表,其中包含3种cloth
和3种color
。
select cloth, avg(Case when color='red' then 1 else 0 end)/ Count(*) * 1.0 As redratio, avg(Case when color='blue' then 1 else 0 end)/ Count(*) * 1.0 As blueratio, avg(Case when color='green' then 1 else 0 end)/ Count(*) * 1.0 As greenratio
from cloth group by cloth
因此,假设字段名称cloth
和color
select cloth, avg(Case when color='red' then 1 else 0 end)/ Count(*) * 1.0 As redratio, avg(Case when color='blue' then 1 else 0 end)/ Count(*) * 1.0 As blueratio, avg(Case when color='green' then 1 else 0 end)/ Count(*) * 1.0 As greenratio
from cloth group by cloth
请尝试:
select cloth, avg(Case when color='red' then 1 else 0 end)/ Count(*) * 1.0 As redratio, avg(Case when color='blue' then 1 else 0 end)/ Count(*) * 1.0 As blueratio, avg(Case when color='green' then 1 else 0 end)/ Count(*) * 1.0 As greenratio
from cloth group by cloth
select
1.0 * sum(color='red')/count(*) as redRatio,
1.0 * sum(color='green')/count(*) as greenRatio,
1.0 * sum(color='blue')/count(*) as blueRatio
from cloth