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 |
dcarva
Posting Yak Master
140 Posts |
Posted - 2012-06-12 : 11:05:30
|
Hello,I have a quick one, I hope. I have a query that returns a set of records as follows:UserID MachineID LastUsed LastHourUsed1 2 20120101 2233 2 20120101 125 4 20120101 116 4 20120101 23I need a select statement that will return one record for each of the two machines (id of 2 and id of 4) based off of the MAX(lasthourused) So I need to have it return:1 2 20120101 226 4 20120101 23No matter how I group it, I get all 4 records. I am trying to avoid running a script to loop through each record and pick the right one. I would prefer SQL. Any hints are appreciated.Thanks! |
|
yosiasz
Master Smack Fu Yak Hacker
1635 Posts |
Posted - 2012-06-12 : 11:15:36
|
[code]declare @dcarva table(UserID int, MachineID int, LastUsed datetime, LastHourUsed int)insert into @dcarvaSELECT 1, 2, '20120101', 22UNIONSELECT 33, 2, '20120101', 12UNIONSELECT 5, 4, '20120101', 11UNIONSELECT 6, 4, '20120101', 23SELECT * FROM (select * , ROW_NUMBER() OVER (PARTITION BY MachineID ORDER BY LastHourUsed DESC) AS Rnfrom @dcarva) Brazilwhere Rn = 1[/code]<><><><><><><><><><><><><><><><><>If you don't have the passion to help people, you have no passion |
 |
|
dcarva
Posting Yak Master
140 Posts |
Posted - 2012-06-12 : 11:23:45
|
Thank you so much. That works like a charm. Interesting way to do it. Thanks! |
 |
|
|
|
|
|
|