首页 > 解决方案 > postgresql while/循环函数

问题描述

有没有办法用 while/loop 函数替换/简化以下代码?我需要在项目<特定数字或变量时循环它。谢谢!

select 
count(distinct wallet) filter (where items >= 3 and items < 6) + 
count(distinct wallet) filter (where items >= 6 and items < 9) + 
count(distinct wallet) filter (where items >= 9 and items < 12) +
count(distinct wallet) filter (where items >= 12 and items < 15) as total_items

from 
agg
where items > 0 

标签: postgresqlloops

解决方案


不,没有办法循环这个。(嗯,有,但它过于复杂并且可能效率低下)。

但是,您可以使用数学将items每组的规范元素减少到一个,然后计算由和各自的规范元素组成的不同元组:wallet

select count(distinct (wallet, items/3)) as total_items
from agg
where items >= 3 and items < 15

推荐阅读