Share via


最初の最後の関数 (Microsoft Access SQL)

適用先: Access 2013 | Access 2016

クエリが返したレコードセットの先頭のレコード、または末尾のレコードのフィールド値を返します。

構文

First( expr )

Last( expr )

expr プレースホルダーは、使用するデータを含むフィールドを識別する文字列式、またはそのフィールド内のデータを使用して計算を実行する式を表します。 expr のオペランドには、テーブル フィールド、定数、または関数の名前を含めることができます (組み込み関数またはユーザー定義関数のいずれかでも、他の SQL 集計関数の 1 つでもかまいません)。

注釈

First 関数および Last 関数は、DAO の Recordset オブジェクトの MoveFirst メソッドおよび MoveLast メソッドに似ています。 これら 2 つの関数は、クエリが返した結果セットの先頭のレコードまたは末尾のレコードに指定しているフィールド値を返すだけです。 これらの関数が返すレコードの順序に特定の法則はなく、クエリに ORDER BY 句の記述がない限り、順序に意味はありません。

次の使用例では、Employees テーブルから返される先頭のレコードと末尾のレコードの LastName フィールドの値を取得します。

この例では、EnumFields プロシージャを呼び出します。EnumFields プロシージャについては、SELECT ステートメントの使用例を参照してください。

Sub FirstLastX1() 
 
    Dim dbs As Database, rst As Recordset 
 
    ' Modify this line to include the path to Northwind 
    ' on your computer. 
    Set dbs = OpenDatabase("Northwind.mdb") 
     
    ' Return the values from the LastName field of the  
    ' first and last records returned from the table. 
    Set rst = dbs.OpenRecordset("SELECT " _ 
        & "First(LastName) as First, " _ 
        & "Last(LastName) as Last FROM Employees;") 
     
    ' Populate the Recordset. 
    rst.MoveLast 
     
    ' Call EnumFields to print the contents of the  
    ' Recordset. Pass the Recordset object and desired 
    ' field width. 
    EnumFields rst, 12 
 
    dbs.Close 
 
End Sub 

次の使用例では、単純に First 関数および Last 関数の使用方法を Min 関数および Max 関数の使用方法と比較しています。ここでは Employees テーブル内で最も早い誕生日と最も遅い誕生日を探します。

Sub FirstLastX2() 
 
    Dim dbs As Database, rst As Recordset 
 
    ' Modify this line to include the path to Northwind 
    ' on your computer. 
    Set dbs = OpenDatabase("Northwind.mdb") 
     
    ' Find the earliest and latest birth dates of 
    ' Employees. 
    Set rst = dbs.OpenRecordset("SELECT " _ 
        & "First(BirthDate) as FirstBD, " _ 
        & "Last(BirthDate) as LastBD FROM Employees;") 
     
    ' Populate the Recordset. 
    rst.MoveLast 
     
    ' Call EnumFields to print the contents of the  
    ' Recordset. Pass the Recordset object and desired 
    ' field width. 
    EnumFields rst, 12 
     
    Debug.Print 
 
    ' Find the earliest and latest birth dates of 
    ' Employees. 
    Set rst = dbs.OpenRecordset("SELECT " _ 
        & "Min(BirthDate) as MinBD," _ 
        & "Max(BirthDate) as MaxBD FROM Employees;") 
     
    ' Populate the Recordset. 
    rst.MoveLast 
     
    ' Call EnumFields to print the contents of the  
    ' Recordset. Pass the Recordset object and desired 
    ' field width. 
    EnumFields rst, 12 
 
    dbs.Close 
 
End Sub 

投稿者について

コミュニティ メンバー アイコン完全アクセス コミュニティは、Microsoft Access Wiki およびヘルプ フォーラムの第一人者です。

関連項目

サポートとフィードバック

Office VBA またはこの説明書に関するご質問やフィードバックがありますか? サポートの受け方およびフィードバックをお寄せいただく方法のガイダンスについては、Office VBA のサポートおよびフィードバックを参照してください。