SQL-按同一表中的3列分组平均值

时间:2020-09-14 15:43:05

标签: mysql sql

我有一个称为属性的表,该表有2列:

  1. prop_type(可能的值:部门,房屋,土地等)
  2. prop_exclusive(可能值:“排他”,“非排他”)

我需要按 prop_type 对记录进行分组,并获得 prop_exclusive 列的平均值数量。

预期结果是:

enter image description here

我的sql语法应该如何?

致谢!

2 个答案:

答案 0 :(得分:2)

您可以使用avg()

select proptype,
       avg( prop_exclusive = 'Exclusive' ) as ratio_exclusive,
       avg( prop_exclusive = 'Nonexclusive' ) as ratio_nonexclusive
from t
group by proptype

答案 1 :(得分:1)

如果确实需要将平均值显示为百分比,则可以按以下方式修改Gordon的解决方案。话虽如此,我强烈建议您将平均值保留为数字数据类型,并在表示层中设置输出格式。

select proptype,
       concat(round(avg( prop_exclusive = 'Exclusive' ) * 100, 0),'%') as ratio_exclusive,
       concat(round(avg( prop_exclusive = 'Nonexclusive' )* 100, 0),'%') as ratio_nonexclusive
from t
group by proptype