共用方式為


MICROSOFT Access SQL) (GROUP BY 子句

適用於:Access 2013 | Access 2016

將指定欄位清單中具有相同值的記錄合併為單一的記錄。 若在 SELECT 陳述式中包含 SQL 彙總函數,例如 SumCount,就會為每一筆記錄建立摘要值。

語法

SELECT fieldlist FROM table WHERE criteria [GROUP BY groupfieldlist ]

包含 GROU BY 子句的 SELECT 陳述式有以下部分:

部分 描述
fieldlist 要與任何欄位名稱別名、SQL 彙總函數、選取述詞 (ALL、DISTINCT、DISTINCTROW 或 TOP) 或其他 SELECT 陳述式選項一起擷取之一個或多個欄位的名稱。
table 擷取記錄來源的資料表名稱。 如需詳細資訊,請參閱 FROM 子句。
criteria 選取準則。 如果陳述式包含 WHERE 子句,則 Microsoft Access 資料庫引擎會在將 WHERE 條件套用至記錄後,對值進行分組。
groupfieldlist 用來將記錄進行群組的欄位 (最多 10 個) 名稱。 groupfieldlist 中的欄位名稱順序決定最高至最低的進行群組層級。

註解

GROUP BY 是選擇性的。

若 SELECT 陳述式中無 SQL 彙總函數,則會省略摘要值。

GROUP BY 欄位中的 Null 值已進行群組且未忽略。 然而,未在任何 SQL 聚合函數中計算 Null 值。

使用 WHERE 子句來排除您不想要分組的資料列,並使用 HAVING 子句來篩選已分組的記錄。

GROUP BY 欄位清單中的欄位除非包含了 Memo 或 OLE 物件資料,否則均可參照任何 FROM 子句所列之任何資料表的任何欄位,即使欄位並不包含在 SELECT 陳述式中 (只要 SELECT 陳述式至少包含一個 SQL 彙總函數)。 Microsoft® Jet 資料庫引擎不能在 Memo 或 OLE 物件欄位中進行群組。

所有在 SELECT 欄位清單中的欄位,既不能包含在 GROUP BY 子句中,也不能包含為 SQL 聚合函數的引數。

範例

本範例會建立唯一職稱以及每一職稱其員工數的清單。 此範例會呼叫 EnumFields 程序,您可以在 SELECT 陳述式範例中找到該程序。

Sub GroupByX1() 
 
    Dim dbs As Database, rst As Recordset 
 
    ' Modify this line to include the path to Northwind 
    ' on your computer. 
    Set dbs = OpenDatabase("Northwind.mdb") 
 
    ' For each title, count the number of employees  
    ' with that title.  
    Set rst = dbs.OpenRecordset("SELECT Title, " _ 
        & "Count([Title]) AS Tally " _ 
        & "FROM Employees GROUP BY Title;") 
     
    ' Populate the Recordset. 
    rst.MoveLast 
     
    ' Call EnumFields to print the contents of the  
    ' Recordset. Pass the Recordset object and desired 
    ' field width. 
    EnumFields rst, 25 
 
    dbs.Close 
 
End Sub 

此範例會針對每個唯一的職稱,計算華盛頓中員工為該職稱的人數。

Sub GroupByX2() 
 
    Dim dbs As Database, rst As Recordset 
 
    ' Modify this line to include the path to Northwind 
    ' on your computer. 
    Set dbs = OpenDatabase("Northwind.mdb") 
     
    ' For each title, count the number of employees  
    ' with that title. Only include employees in the  
    ' Washington region. 
    Set rst = dbs.OpenRecordset("SELECT Title, " _ 
        & "Count(Title) AS Tally " _ 
        & "FROM Employees WHERE Region = 'WA' " _ 
        & "GROUP BY Title;") 
     
    ' Populate the Recordset. 
    rst.MoveLast 
 
    ' Call EnumFields to print the contents of the  
    ' Recordset. Pass the Recordset object and desired 
    ' field width. 
    EnumFields rst, 25 
 
    dbs.Close 
 
End Sub 

另請參閱

支援和意見反應

有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應