2

I have two files: apt, and appointment_history. The second file has multiple records referencing single records in apt.

How to I get only the last record in appointment history that is referencing the record in apt from within the subquery?

Edit#1: The question is not so much how to group, but rather how to pass an outside value (appointment_recid) into the subquery without grouping the entire appointment_history file on non-used appointment_recid's. So I don't think this is a duplicate question. (Although being a noobie, it might turn out the same).

PostgreSQL 9.3

ERROR: invalid reference to FROM-clause entry for table "apt" SQL state: 42P01 Hint: There is an entry for table "apt", but it cannot be referenced from this part of the query.

select apt.*, h.* 
    from apt 
    join appointment_history h on (h.appointment_recid = apt.appointment_recid)
    join ( 
        select max(tposted) as tposted 
        from appointment_history a 
        where a.appointment_recid = apt.appointment_recid) currenthx 
    on (currenthx.tposted = h.tposted)

TIA

Alan Wayne
  • 5,122
  • 10
  • 52
  • 95

2 Answers2

1
select apt.*, h.* 
    from apt 
    join appointment_history h 
      on (h.appointment_recid = apt.appointment_recid)
    join ( 
           SELECT appointment_recid, max(tposted) as tposted 
           FROM appointment_history a
           GROUP BY  appointment_recid  -- ADD GROUP BY 
         ) currenthx 
      on currenthx.tposted = h.tposted
     and currenthx.appointment_recid = a.appointment_recid   -- JOIN OUTSIDE

For request

select apt.*, h.* 
    from apt 
    join appointment_history h 
      on (h.appointment_recid = apt.appointment_recid)
    join ( 
           SELECT appointment_recid, max(tposted) as tposted 
           FROM appointment_history a
           JOIN apt ap
               on (h.appointment_recid = ap.appointment_recid)               
           GROUP BY  appointment_recid  -- ADD GROUP BY 
         ) currenthx 
      on currenthx.tposted = h.tposted
     and currenthx.appointment_recid = a.appointment_recid   -- JOIN OUTSIDE
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
1

In the absence of detailed table information, this probably solves your issue:

SELECT apt.*, h.* 
FROM apt
JOIN (
  SELECT <columns>, max(tposted) AS tposted 
  FROM appointment_history
  GROUP BY <columns>) h USING (appointment_recid);
Patrick
  • 29,357
  • 6
  • 62
  • 90
  • ...+1 for demonstrating USING clause to this noobie. Thanks. Grouping on all the columns won't give me the most recent record however when I want only those records for a specific appointment_recid. – Alan Wayne Jan 28 '16 at 19:53