Sunday, February 12, 2012

Best way to do this query

I have a Customer table and an Events table. Whenever a customer attends an
event, a row is added to the Events table, which has CustomerID, EventName
and EventDate fields.
I want a query that returns all the customers but only the most recently
attended event. In other words, I want the query to ignore events other than
the most recently attended by each customer.
The (simplified) tables are:
Customer:
ID
Name
Events:
ID
CustomerID
EventName
EventDate
Any suggestions for the best way to do this?
TimTim,
You could use something like this:
(Untested)
Select Customer.ID, Customer.Name, Events.ID, Events.EventName,
Events.EventDate
>From Customer
Join Events on Customer.ID = Events.CustomerID
Where Events.EventDate =
(Select Max(Events2.EventDate) From Events Events2 Where
Events2.CustomerID = Customer.CustomerID)
HTH
Barry|||"Barry" <barry.oconnor@.singers.co.im> wrote in message
news:1129053565.927048.54860@.o13g2000cwo.googlegroups.com...

> Select Customer.ID, Customer.Name, Events.ID, Events.EventName,
> Events.EventDate
> Join Events on Customer.ID = Events.CustomerID
> Where Events.EventDate =
> (Select Max(Events2.EventDate) From Events Events2 Where
> Events2.CustomerID = Customer.CustomerID)
Good suggestion. Thanks.
Tim

No comments:

Post a Comment