Share via


Group By 子句 (Visual Basic)

群組查詢結果的項目。 也可以用來將彙總函式 (Aggregate Function) 套用至每個群組。 群組作業是根據一個或多個索引鍵。

Group [ listField1 [, listField2 [...] ] By keyExp1 [, keyExp2 [...] ]
  Into aggregateList

組件

詞彙

定義

listField1, listField2

選擇項。 明確識別要納入群組結果之欄位的一個或多個查詢變數的欄位。 如果未指定欄位,所有查詢變數的欄位都會納入群組結果。

keyExp1

必要項。 識別用以判斷項目群組之索引鍵的運算式。 您可以指定一個以上的索引鍵,藉以指定複合索引鍵。

keyExp2

選擇項。 與 keyExp1 結合以建立複合索引鍵的一個或多個額外索引鍵。

aggregateList

必要項。 識別群組彙總方式的一個或多個運算式。 若要識別群組結果的成員名稱,請使用下列格式的 Group 關鍵字:

Into Group

-或-

Into <alias> = Group

您也可以加入彙總函式,以便套用至群組。

備註

您可以使用 Group By 子句,將查詢結果分成數個群組。 群組作業是根據索引鍵,或由多個索引鍵所組成的複合索引鍵。 與相符索引鍵值關聯的項目,就會加入相同的群組。

使用 Into 子句的 aggregateList 參數和 Group 關鍵字,可以識別用於參考群組的成員名稱。 您也可以將彙總函式加入 Into 子句以計算群組項目的值。 如需標準彙總函式的清單,請參閱 Aggregate 子句 (Visual Basic)

範例

下列程式碼範例會根據客戶的位置 (國家) 將客戶的清單進行分組,並提供每個群組中的客戶計數。 結果是以國家名稱排序。 群組結果則是以城市名稱排序。

Public Sub GroupBySample()
  Dim customers = GetCustomerList()

  Dim customersByCountry = From cust In customers
                           Order By cust.City
                           Group By CountryName = cust.Country
                           Into RegionalCustomers = Group, Count()
                           Order By CountryName

  For Each country In customersByCountry
    Console.WriteLine(country.CountryName &
                      " (" & country.Count & ")" & vbCrLf)

    For Each customer In country.RegionalCustomers
      Console.WriteLine(vbTab & customer.CompanyName &
                        " (" & customer.City & ")")
    Next
  Next
End Sub

請參閱

參考

Select 子句 (Visual Basic)

From 子句 (Visual Basic)

Order By 子句 (Visual Basic)

Aggregate 子句 (Visual Basic)

Group Join 子句 (Visual Basic)

概念

Visual Basic 中的 LINQ 簡介

其他資源

查詢 (Visual Basic)