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 |
|
pvccaz
Yak Posting Veteran
87 Posts |
Posted - 2009-02-23 : 12:41:33
|
| Hi,I have a table with 3 cols:Id Number expense12 Sam 5613 Sam 8978 Sam NULLI want to get the row which has the maximum id and the columns thatare assoicated with it. (The Id is a unique column).Output should be:Id Number expense78 Sam NULLI am trying to use the max function with the group.. but having trouble getting thecorrect result. Can any ideas please? |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-02-23 : 12:48:51
|
select id, number, expensefrom (select id, number, expense, row_number() over (partition by number order by id) as recidfrom table1) as fwhere recid = 1 E 12°55'05.63"N 56°04'39.26" |
 |
|
|
pvccaz
Yak Posting Veteran
87 Posts |
Posted - 2009-02-23 : 13:01:45
|
| Thanks so much Peso..!!Since i wanted the maximum id i just changed the query to include descending order. "partition by number order by id desc" . It gives the max id.Thanks much!. |
 |
|
|
Nageswar9
Aged Yak Warrior
600 Posts |
Posted - 2009-02-23 : 23:16:36
|
| Also Try This,declare @temp table (Id int, Number varchar(32), expense int)insert into @tempselect 12, 'Sam', 56 union allselect 13, 'Sam', 89 union allselect 78, 'Sam', NULLselect maxid,number,expense from @temp tinner join ( select max(id) maxid from @temp) t1 on t.id = t1.maxid |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-02-24 : 09:18:18
|
quote: Originally posted by Nageswar9 Also Try This,declare @temp table (Id int, Number varchar(32), expense int)insert into @tempselect 12, 'Sam', 56 union allselect 13, 'Sam', 89 union allselect 78, 'Sam', NULLselect maxid,number,expense from @temp tinner join ( select number,max(id) maxid from @temp) t1 on t.id = t1.maxid and t.number=t1.number
small modification if op is looking for max id corresponding to each number |
 |
|
|
|
|
|
|
|