First Record by Date

S

Shoelaces

I have a table that stores events:
eventname
url
planner
eventdate
etc.

I have a query of this table that sorts first by planner and then by date.
SELECT eventname, eventurl, planner, eventdate
FROM events
ORDER BY planner, eventdate;

I have a need now to create a query that would return only the first record
for each planner.

Each planner can have multiple events. I am interested, presently, in only
the first (by date) event for each planner.

I thought "min" might prove helpful, but I get an error that eventname isn't
part of the aggregate.

SELECT eventname, eventurl, planner, min(eventdate) AS FirstDate
FROM events
ORDER BY planner, eventdate;

How do I construct the query to disregard the other events for each planner?
Or perhaps better, how do I construct the query to pull only the first event
for each planner? I am not great with SQL, so any handholding you can offer
will be appreciated.

Thanks!
 
O

Ofer

Try this

SELECT M1.*
FROM TableName AS M1
WHERE M1.eventdate In (SELECT Top 1 M2.eventdate
FROM TableName as M2
WHERE M2.planner =M1.planner
ORDER BY M2.eventdate)
 
J

Jerry Whittle

You were almost there!
Change ORDER BY planner, eventdate
to
GROUP BY eventname, eventurl, planner
 
M

Marshall Barton

Shoelaces said:
I have a table that stores events:
eventname
url
planner
eventdate
etc.

I have a query of this table that sorts first by planner and then by date.
SELECT eventname, eventurl, planner, eventdate
FROM events
ORDER BY planner, eventdate;

I have a need now to create a query that would return only the first record
for each planner.

Each planner can have multiple events. I am interested, presently, in only
the first (by date) event for each planner.

I thought "min" might prove helpful, but I get an error that eventname isn't
part of the aggregate.

SELECT eventname, eventurl, planner, min(eventdate) AS FirstDate
FROM events
ORDER BY planner, eventdate;

How do I construct the query to disregard the other events for each planner?
Or perhaps better, how do I construct the query to pull only the first event
for each planner?


I think this may be what you want (but I'm not sure if
eventname or eventurl is is the key field):

SELECT eventname, eventurl, planner, eventdate AS FirstDate
FROM events
WHERE eventdate = (SELECT min(X.eventdate)
FROM events As X
WHERE X.eventname = events.eventname)
ORDER BY planner, eventdate
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top