Link to home
Start Free TrialLog in
Avatar of Michael Sole
Michael Sole

asked on

Get the top row of a group by date in a SQL join

I have 3 tables and I need to get the most recent row of the middle table in a join.

Table1 - Categories
ID - PK
Name - Varchar

Table2 - CatAction
ID - PK
CID - Int FK to ID in Categories
AID - Int FK to ID in Actions
last_run - date/time

Table 3 - Actions
ID - PK
Name - Varchar

When an "action" fires it updates the last_run field in CatAction by cid with the time it ran. I need to select all fields but only the last_run action by category. This is NOT what I want, but it shows the relationships of the tables

select * from categories c
LEFT JOIN cataction ca ON c.id=ca.cid
LEFT JOIN action a ON ca.aid=c.id

I also need a query that will count the number of actions by type by last run time. So I will need to group by action id as well.
ASKER CERTIFIED SOLUTION
Avatar of ralmada
ralmada
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
and like this for the second part
select a.id, count(*) from categories c
LEFT JOIN (
	select * from cataction t1
	where last_run = (select max(last_run) from cataction where cid = t1.cid)
) ca ON c.id=ca.cid
LEFT JOIN action a ON ca.aid=c.id
group by a.id

Open in new window