oracle group by ,count,sum 函式 日常使用小知識
阿新 • • 發佈:2019-02-03
Oracle中group by用法
在select 語句中可以使用group by 子句將行劃分成較小的組,一旦使用分組後select操作的物件變為各個分組後的資料,在用分組時使用聚組函式返回的是每一個組的彙總資訊。列 :select o.customer_no customer_no,count(o.customer_no) as total ,sum(o.amount) as totalAmountfrom pos_order o where o.status != 'INIT'and o.create_time > to_date('20170801','yyyymmdd')
and o.create_time < to_date('20170901','yyyymmdd')
group by o.customer_no
total 以及totalAmount 是對customer_no分組後的統計與求和
使用having子句 限制返回的結果集。group by 子句可以將查詢結果分組,並返回行的彙總資訊Oracle 按照group by 子句中指定的表示式的值分組查詢結果。在帶有group by 子句的查詢語句中,在select 列表中指定的列要麼是group by 子句中指定的列,要麼包含聚組函式 select max(sal),job emp group by job; (注意max(sal),job的job並非一定要出現,但有意義) 查詢語句的select 和group by ,having 子句是聚組函式唯一出現的地方,在where 子句中不能使用聚組函式
having 子句的作用是篩選滿足條件的組,having即在分組之後過濾資料,條件中經常包含聚合函式
使用order by排序時order by子句置於group by 之後 並且 order by 子句的排序標準不能出現在select查詢之外的列。意思就是order by 後面的欄位必須要出現在select列表中的,
查詢每個部門的每種職位的僱員數
select deptno,job,count(*) from emp group by deptno,job
/****************************************************************
記住這就行了:
在使用group by 時,有一個規則需要遵守,即出現在select列表中的欄位,如果沒有在組函式中,那麼必須出現在group by 子句中。(select中的欄位不可以單獨出現,必須出現在group語句中或者在組函式中。)
count 記數
count統計的是欄位一共有多少行資料。select count(a.agent_no) from agent a 意思就是customer_no 這個欄位下一共有多少行資料
用count統計agent_no有多少行資料
sum 求和
sum是求指定欄位下所有資料的相加總和 select sum(o.amount) from pos_order o 意思就是求出amount這個欄位下的資料總和