Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Select Distinct

I have a problem that probably has a very easy solution, but perhaps I'm too fried from 16 hours work days to figure it out.

I have a Status table that references support tickets. Every time something is done to a ticket, a new status record gets inserted with a foreign key of the ticket ID. Whenever I need to find out the latest status, I use a query that selects the top status like this:

SELECT Top 1 StatusID
FROM Status
WHERE TicketID_FK = [ticketid]
ORDER BY StatusID DESC

That's a no-brainer. However, now, I need to run a query to find ALL DISTINCT TicketID_FK's in Status, but when it selects a DISTINCT TicketID_FK, I want it to select the one with the highest StatusID.

For instance, if the following data exists in the table:

StatusID TicketID_FK
1 20
2 20
3 20
4 21
5 21
6 21
7 21

I want the query that would give me a recordset like this:

TicketID_FK = 20 StatusID = 3
TicketID_FK = 21 StatusID = 7

Can this be done with a SQL query, or will it have to be sorted some other way using code within the page?

Thank you in advance to anyone that can help.

Derrick
[1435 byte] By [dphilips] at [2007-11-11 7:59:58]
# 1 Re: Select Distinct
Try:

SELECT TicketID, Max(StatusID)
FROM Status
GROUP BY TicketID;
Phil Weber at 2007-11-11 23:47:20 >
# 2 Re: Select Distinct
Phil, from the bottom of my tired and weary heart, Thank you! I'm ashamed I didn't figure this out. I almost did, but while experimenting with different queries I kept trying to pull in all the other fields as well while trying to keep TicketID distinct, and now I see that that's likely not possible (in a query). I will probably end up just running another query within the loop to pull the rest of the info out (like DateCreated, AuthorID, etc.). Probably not the most efficient way, but I need to get this project done so I can get some SLEEP!

Thanks again.

Derrick
dphilips at 2007-11-11 23:48:25 >
# 3 Re: Select Distinct
You can probably pull the related fields in the same query if you put the DISTINCT in a subquery. See if this helps: http://forums.dev-archive.com/showthread.php?t=150181
Phil Weber at 2007-11-11 23:49:25 >