开发者

Access SQL join question

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    | 开发者_如何学Cabc | 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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜