如何对组中的行进行求和,然后根据总和过滤行

时间:2017-03-28 11:56:10

标签: postgresql

我想查找按type列分组的表格中所有正值的总和和计数。我只对sum >= 10count >= 2

的情况感兴趣

例如,

type  |  value 
------+-------
A     | 10
B     | 5
C     | 7
B     | 5
C     | 6
C     | -1
D     | 3
D     | 4

我想要结果

type  | sum  | count
------+------+------
B     | 10   | 2
C     | 13   | 2

A不应该有一行,因为count只会是1D不应该有一行,因为sum只会是7。应该完全忽略否定value

我认为答案应该是这样的:

select type, sum(value) as sum, count(value) as count
from my_table
where value > 0
group by type
having sum >= 10 and count >= 2

但我不确定如何正确组合所有相关条件。

1 个答案:

答案 0 :(得分:0)

select type, sum(value) as sum, count(type) as count
from my_table
where value > 0
group by type
having sum(value) >= 10 and count(type) >= 2