1.17 分组:筛选时用到分组汇总值

 

有分类产品销售额汇总表如下,请找出销售额大于所在分类平均销售额的产品:

CategoryName ProductName ProductSales
Beverages C?te de Blaye 46563.09
Beverages Chai 4887
Beverages Chang 7038.55
Beverages Chartreuse verte 4475.7
Beverages Guaraná Fantástica 1553.63

脚本:

A
1 =connect(“db”)
2 =A1.query@x(“select * from ProductSales”)
3 =A2.group(CategoryName)
4 =A3.((a=~.avg(ProductSales),~.select(ProductSales>a))).conj()

A1 连接数据库
A2 读取分类产品销售额汇总表
A3 按产品分类分组,并产生分组子集
A4 对着分组子集循环计算平均销售额赋给临时变量 a,然后再筛选出销售额大于 a 的记录,最后合并

运行结果:

CategoryName ProductName ProductSales
Beverages C?te de Blaye 46563.09
Beverages Ipoh Coffee 11069.9
Condiments Chef Anton’s Cajun Seasoning 5214.88
Condiments Gula Malacca 6543.45
Condiments Louisiana Fiery Hot Pepper Sauce 9331.08