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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window