R prod函数,但是在SQL中,如何取一组乘积

问题描述

在R中,可以像这样进行一组乘积的乘积:

 iris %>% group_by(Species) %>% summarize(new_col = prod(Petal.Length))

如何在postgresql或dbplyr / dplyr中实现相同的概念?

解决方法

不幸的是,SQL标准没有定义聚合的“产品”功能。但是,您可以使用算术解决此问题。

假设您要在表petal_length中共享相同的species的行组中计算mytable的乘积:

select species,exp(sum(ln(petal_length))) petal_length_product
from mytable
group by species

只要petal_length的所有值都大于0,此方法就起作用。