天天看點

Oracle查詢中使用分組函數

有時需要對查詢對象中相同屬性的行進行分組,然後檢視分類後行的統計資訊;

例如:财務報表中需要統計各個部門每年開銷,那麼就要已部門進行分類,然後在員工工資表中将同各部門的員工工資進行求和;

下面進行分類說明:

使用group by 子句對行進行分組

以products表為例,select * from products

Oracle查詢中使用分組函數

1、查詢同一個産品類型的商品個數

select pp.product_type_id,count(pp.product_id) from products pp

group by pp.product_type_id

Oracle查詢中使用分組函數

2、使用多列進行分組

select * from purchases;

Oracle查詢中使用分組函數

分别通過使用者和使用者購買産品ID進行分類

select pp.customer_id,pp.product_id from purchases pp 

group by pp.customer_id,pp.product_id;

Oracle查詢中使用分組函數

3、使用order by 子句對分組進行排序

如上2的sql,按照customer_id進行排序

select pp.customer_id,pp.product_id from purchases pp 

group by pp.customer_id,pp.product_id

order by pp.customer_id;

Oracle查詢中使用分組函數

使用聚合函數的錯誤用法:

(1)當查詢語句中包含一個聚合函數時,而所選擇的列并不在聚合函數中,那麼這些列就必須在group by子句中,否則就會報錯;

如:select pp.product_type_id,sum(pp.price) from products pp;

ORA-00937: not a single-group group function

(2)不能在where子句中使用聚合函數來限制行,如果這樣就會包ORA-00934錯誤;

如:select pp.product_type_id,sum(pp.price) from products pp where sum(pp.price) > 100 group by pp.product_type_id;

ORA-00934: group function is not allowed here

4、使用having子句過濾進行分組

如上(2)情況,需要使用having子句進行分組條件過濾;

having子句的整體格式如下

select ...

from....

where ...

group ....

having...

order by ...

如上products表,根據産品類型進行分類,并計算每個分類中産品價格小于15元的記錄的平均值,然後将平均值大于13的分組顯示出來,并按照平均值的大小進行排序;

如:select pp.product_type_id, avg(pp.price)

  from products pp

 where pp.price < 50

 group by pp.product_type_id

 having avg(pp.price)>20

 order by avg(pp.price);

Oracle查詢中使用分組函數