问题描述
在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
,此方法就起作用。