資料庫之分組函數

來源:互聯網
上載者:User
 分組函數對一組資料進行運算,針對一組資料(多行記錄)只返回 一個結果,也稱多行函數。
 
  常用的分組函數
        函數      功能說明                適用類型
        avg()    計算平均值              數值型
        count()  返回查詢所得到的記錄行數 任何資料類型
        max()    計算最大值              任何資料類型
        min()    計算最小值              任何資料類型
        sum()    求和                    數值型

  count()函數
      count(*)返回組中總記錄數目;
      count(exp) 返回運算式exp值非空的記錄數
      count(distinct(exp))返回運算式exp值不重複的,非空的記錄數目。
      舉例:
      select count(*) from emp;
      select count(comm) from emp;
      select count(distinct(deptno)) from emp;
 
  分組函數與空值
      分組函數省略列中的空值
      select avg(comm) from emp;
      select sum(comm) from emp;

      可使用NVL()函數強制分組函數處理空值
      select avg(nul(comm,0)) from emp;
      select sum(nul(comm,0))/count(comm) from emp;

group by 字句
   
    group by 子句將資料分成若干小組
    文法格式
      select column ,group_function(column)
      from  table
      [where condition]
      [group by group_by_expression]
      [order by column]
    舉例:
  select deptno ,avg(sal) from emp group by deptno;
  select deptno ,avg(sal) from emp where hiredate>'20-4月-81'
group by deptno;
  select deptno,job,avg(sal) from emp group by deptno,job order by demptno desc;
    說明:
      1。出現在select列表中的欄位,如果不是包含在組函數中,那麼該欄位必須同時在group by字句中出現
      2。包含在group by 字句中的欄位則不必須出現在select列表中
      3  可使用where字句限定查詢條件
      4 可使用order by 字句指定排序方式

having子句
    子句用於過濾分組
    文法格式:
        select column,group_function(column)
        from  table
        [where condition]
        [group by  group_by_expression]
        [having  group_condition]
        [order by column]

    舉例:
      select  deptno,job,avg(sal)
      from  emp
      where  hiredate>=to_date('1981年05月01','yyyy-mm-dd')
      group by  deptno,job
      having avg(sal)>1200
      order by deptno,job;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.