Results 1 to 3 of 3
  1. #1
    dbc23 is offline Novice
    Windows 7 64bit Access 2016
    Join Date
    Jan 2019
    Posts
    11

    Can't quite grok a Sub-Query

    I know a sub-query is the solution to my problem, but I can't manage to wrap my head around how the SQL integrates into the query as built by QBE.

    I have 2 tables:

    CompletedDrives
    DriveResults

    The fields I'm referencing are:


    CD.DriveID
    CD.Date
    CD.Account
    DR.TotalResults

    They're Joined on a field "DriveID"

    What I need is to return the average of the 3 most recent drives by account.

    *Pseudo code*
    FOR Each CD.Account
    Select 3 most recent DriveIDs by Date
    Average the TotalResults of those 3 drives from DriveResults
    Return As:
    Account | AverageOf3Drives

    This should be super simple from everything I've read but I'm very new to SQL and am used to using the QBE

    ANY help is appreciated,
    Aaron

  2. #2
    ranman256's Avatar
    ranman256 is offline VIP
    Windows Vista Access 2010 32bit
    Join Date
    Apr 2014
    Location
    Kentucky
    Posts
    9,549
    wow, shout out to Heinlein.
    Note you don't loop thru data in access, that's what queries are for.

    the subform query can pull all records, BUT if you bind the subform to the master form on the key field,
    then the subform only shows records with the master Key.
    LINK MASTER FIELDS
    LINK CHILD FIELDS

    For most recent items, you need 2 queries:
    Q1 get the largest: select top 3 ID, Max(Date) from table.
    Q2 get all records: join table to Q1 on ID and get all the data.

  3. #3
    ssanfu is offline Master of Nothing
    Windows 7 32bit Access 2010 32bit
    Join Date
    Sep 2010
    Location
    Anchorage, Alaska, USA
    Posts
    9,664
    You could use two queries as suggested by ranman.

    Or you could use a sub query. See "Subquery basics" by Allen Browne

Please reply to this thread with any new information or opinions.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums