Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
k_shehadeh
Starting Member
3 Posts |
Posted - 2007-10-10 : 16:00:41
|
Let's say you have a status table that looks like this:DeviceID | DriveStatus | Time --------------------------------- 1 Bad 10/10/2007 2 Bad 10/9/2007 3 Good 10/9/2007 1 Good 10/8/2007 2 Good 10/7/2007 I need to write a query that gets the most recent DriveStatus for devices with ID 1 and 2. So the problem here is that I can't use ORDER BY DESC on Time because there are multiple devices here. So how do I pick out the most recent status for devices 1 and 2?This problem has been plaguing me for a while and I'd like to get a solution once and for all. Thanks! |
|
|
Kristen
Test
22859 Posts |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2007-10-10 : 16:35:33
|
| Be careful with that column that looks like a dateThis query produces two different results if Time is a varchar and time as datetime.SELECT a.DeviceID,a.DriveStatus,a.TimeFROM @tbl aINNER JOIN(select DeviceId ,[Time] = max(time) from @tblwhere deviceid < 3group by DeviceID) bON a.deviceid = b.deviceidand a.time = b.timeJim |
 |
|
|
k_shehadeh
Starting Member
3 Posts |
Posted - 2007-10-11 : 13:49:03
|
| Thanks very much for the info. That thread pointed me down the right path - I should note that I have the added obstacle of having to make these queries work with Access as well which forced me to tweak the final query. But all is well - at least it looks like it is. Thanks again. |
 |
|
|
Kristen
Test
22859 Posts |
Posted - 2007-10-11 : 15:26:12
|
| "I have the added obstacle of having to make these queries work with Access as well"Best to ask questions in the Access forum, rather than the "Transact-SQL (2005)" forum please.Kristen |
 |
|
|
k_shehadeh
Starting Member
3 Posts |
Posted - 2007-10-11 : 15:57:01
|
| Hm. But it needs to work with both SQL and Access. |
 |
|
|
Kristen
Test
22859 Posts |
Posted - 2007-10-11 : 16:50:54
|
| Hopefully the answer I posted earlier helped with your SQL Solution. Sorry, but I have no knowledge of how to help with the Access solution.Kristen |
 |
|
|
|
|
|