Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access SQL join question

Tags:

sql

ms-access

Using MS Access. I'm sorry that the title is vague--i just don't exactly know how to describe what type of problem this is, I just know that I need to join two tables or queries to solve it.

I have a OrgHistory table that shows which organization each person (by ID) joined on a certain date (you can only be a member of one org at a time):

Person | Org | JoinDate
-----------------------
123    | abc | 3/2/2011
456    | abc | 4/23/1925
123    | def | 5/12/2011

I also have an Activities table:

Person | Activity | ActivityDate
--------------------------------
123    | eat      | 3/23/2011
123    | sleep    | 6/25/2011
456    | walk     | 7/20/1985

I want to find out, for each record in Activities, which organization the person was a member of on the date of the activity. I'm thinking this might involve converting the JoinDate values into a set of ranges and matching ActivityDate to the appropriate interval, but I'm a little confused about how to design the query in this case--how do I create ranges and match an individual value to a range?

I don't think partition() will work because I'm not trying to hold multiple JoinDate values in a known quantity of buckets.

like image 713
sigil Avatar asked Sep 14 '11 21:09

sigil


People also ask

How do I create a join query in Access?

In query Design view, double-click the join you want to change. The Join Properties dialog box appears. In the Join Properties dialog box, note the choices listed beside option 2 and option 3. Click the option that you want to use, and then click OK.

What are the 3 types of joins in SQL?

Different Types of SQL JOINs (INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.

How do you join two tables in Access?

First, create a new query and add all 3 tables to the query. Right click on the "join line" between the Employees table and the Orders Table and select "Properties" from the popup menu. When the Join Properties window appears, select the second option and click on the OK button.


1 Answers

I can't promise this is the most efficient way, but it works in Access with the test data you provided:

SELECT a.person, a.activity, 
       (
        SELECT TOP 1 org 
          FROM orghistory AS o 
         WHERE o.person = a.person 
               AND o.joindate <= a.activitydate 
         ORDER 
            BY o.joindate DESC
       ) AS Org
  FROM activities AS a;
like image 97
Banjoe Avatar answered Sep 28 '22 18:09

Banjoe