Results 1 to 2 of 2
  1. #1
    kd2017 is offline Well, I tried at least.
    Windows 10 Access 2016
    Join Date
    Jul 2017
    Posts
    1,165

    Select Second Newest Record Within A Group

    I have table [A] that has many of table [B]. Table [B] has a date field [d], and the fields I'm really after f1 and f2 (and, of course, a foreign key field [a_id]).




    For each row in table [A], or grouped by [a_id], I need to select the second record in table [B] ordered by [B]'s date field [d]. I say record because I do need to return 2 fields from table [B] where [B]'s date is 2nd in it's group.

    What's the most efficient way to accomplish this?

    The best I've come up with is to create a two nested subqueries for each value I need to return. This seems inefficient.

    Code:
    SELECT
      A.*,
      (
        SELECT B1.f1
        FROM B AS B1
        WHERE B1.a_id=A.a_id
        AND B1.d <
        (
          SELECT Max(B2.d)
          FROM B AS B2
          WHERE B2.a_id=A.a_id
        )
      ) AS B_f1,
      (
        SELECT B1.f2
        FROM B AS B1
        WHERE B1.a_id=A.a_id
        AND B1.d <
        (
          SELECT Max(B2.d)
          FROM B AS B2
          WHERE B2.a_id=A.a_id
        )
      ) AS B_f2
    FROM A
    As you can see I'm calling subqueries multiple times to return fields from the same row.

  2. #2
    Join Date
    Apr 2017
    Posts
    1,792
    Create a named query p.e.
    qTop1B = SELECT b_id, MAX(d) FROM B GROUP BY b_id;

    Create another named query p.e.
    qTop2B = SELECT b_id, MAX(d) FROM B b LEFT JOIN qTop1B b1 ON b1.b_id = b.b_id WHERE b.d < b1_d GROUP BY b.b_id;
    (i'm using LEFT JOIN for case there is only one row for some b_id);

    Now create your query using JOIN's (left/right inner joins or outer join depending you have one-to-many or one-to-one relationships) to link A, B, and qTop2B together. You never know, but there is a possiblility that with joined tables they are queried at start of query once, instead for every row in A as with your current syntax.
    Last edited by ArviLaanemets; 09-07-2017 at 12:44 PM.

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

Similar Threads

  1. Replies: 2
    Last Post: 01-27-2016, 08:38 AM
  2. Replies: 6
    Last Post: 06-09-2015, 09:51 AM
  3. Replies: 14
    Last Post: 01-14-2015, 07:44 AM
  4. Form is not displaying newest record first
    By JeroenMioch in forum Programming
    Replies: 1
    Last Post: 02-07-2013, 02:32 PM
  5. Select newest Record
    By jbailey4545 in forum Queries
    Replies: 6
    Last Post: 06-22-2012, 01:58 PM

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