通過having代替where來使用count(1),sum()等函數。
譬如如下數據
id value
1 2
1 3
2 3
3 5
3 6
可以寫個語句統計value的分組
select id,sum(value) from table group by id having sum(value)>=5
在這里,可以省略前面的sum(value)。成這樣
select id from table group by id having sum(value)>=5
這樣的結果就是
1 5
3 11
其實這句的意思就是
select id,sum(value) from table where sum(value)>=5 group by id
但是oracle中,計算字段沒法當作條件來用,所以就用having 來表示
count(*)也是一個道理的,當然什么avg,max,min之類的聚合函數也同樣。
比如:存在這個表a1。
A1 B1
2 4
2 4
12 41
12 231
112 31。
要想求出重復的字段。可以用這種方法:
select a1.b1,count(a1.b1) from a1 group by a1.b1 having count(a1.b1)>=2
最后結果是:
B1 COUNT(A1.B1)
4 2