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 |
|
johsulli
Starting Member
1 Post |
Posted - 2008-09-23 : 15:50:35
|
| If anyone can help, this is very basic, it's appreciated.Let’s say I have the following table:Event_id Oper_Name Action1 James Make Account2 James Make Account3 James Fund Account4 James Create User5 James Write Data1 John Write Data2 John Create User3 John Fund AccountI want to get the Action where the Operator ID is James and the Event ID is the highest (max). In this case, I want the row:5 James Write DataCurrently I perform two statements:1.) Select max(event_id) from table where oper_name = James.2.) Select Action from table where oper_name = James AND event_id = the max I retrieved.I get bad syntax if I try to say AND event_id = max(event_id). Is there a way to do this with one statement for the sake of performance?Thanks. |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
|
raky
Aged Yak Warrior
767 Posts |
Posted - 2008-09-24 : 01:26:31
|
| If you are using Sqlserver 2005 then use the belowdeclare @Demo table ( Event_id int ,Oper_Name Varchar(30),Action Varchar(256))insert into @demoselect 1, 'James', 'Make Account' union allselect 2, 'James', 'Make Account' union allselect 3, 'James', 'Fund Account' union allselect 4, 'James', 'Create User' union allselect 5, 'James', 'Write Data' union allselect 1, 'John', 'Write Data' union allselect 2, 'John', 'Create User' union allselect 3, 'John', 'Fund Account'--select * from @demoselect d.Event_Id,d.Oper_Name, d.Action from ( select row_number() over ( partition by oper_name order by event_id desc ) as sno , event_id,oper_name,action from @demo ) dwhere d.sno = 1 and d.oper_name = 'James' |
 |
|
|
james_wells
Yak Posting Veteran
55 Posts |
Posted - 2008-09-28 : 19:53:12
|
| orSelect O.Event_id,O.Oper_Name,O.Actionfrom @demo Owhere O.event_id = (Select max(I.event_id) from @demo I where I.oper_name = O.oper_name)and O.oper_name = 'James' |
 |
|
|
khasim76
Starting Member
35 Posts |
Posted - 2008-09-29 : 00:56:48
|
| COULD SOMEBODY EXPLAIN CODE RETURN BY RAKY .ITS VERY INTERESTING...PLZ ESPECIALLY PARTION BY THAT PART. THANKS |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
|
|
sunil
Constraint Violating Yak Guru
282 Posts |
Posted - 2008-09-29 : 01:19:34
|
| Read row_number() function in sql server 2005 Books Online. |
 |
|
|
|
|
|
|
|