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 |
|
Out_of_my_Depth
Starting Member
1 Post |
Posted - 2009-06-09 : 10:26:30
|
Hi,I am trying to create a query which will bring back the highest two numbers in a column for every single row of relevant information.E.g Table structureTable 1PROCESS_INST_ID - uniqueTable 2ACTIVITY_INST_ID - uniqueACTIVITY_ID - relates to Table 3PROCESS_INST_ID - relates to table 1Table 3ACTIVITY_ID - uniqueACTIVITY_NAMEso table has records likeTable 1PROCESS_INST_ID100Table 2ACTIVITY_INST_ID ACTIVITY_ID PROCESS_INST_ID100 3 100101 1 100102 2 100103 4 100Table 3ACTIVITY_ID ACTIVITY_NAME1 Act 12 Act 23 Act 34 Act 4So, I want to return the activities associated with ACTIVITY_INST_ID 102 and 103, being last two "actions" for process_inst_id 100 (activity_inst_id is incrementing number so always want the last two for any Process_inst_id)so something like PROCESS_INST_ID ACTIVITY_ID 1 ACTIVITY_NAME 1 ACTIVITY_ID 2 ACTIVITY_NAME 2100 4 Act 2 2 Act 2Any help or suggestions would be greatly appreciated Kris |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2009-06-09 : 11:23:35
|
| declare @t table (ACTIVITY_INST_ID int, ACTIVITY_ID int ,PROCESS_INST_ID int)insert @t select 100, 3, 100 union allselect 101, 1, 100 union allselect 102, 2, 100 union allselect 103, 4, 100declare @r table (ACTIVITY_ID int ,ACTIVITY_NAME varchar(20))insert @rselect 1, 'Act 1' union allselect 2, 'Act 2' union allselect 3, 'Act 3' union allselect 4, 'Act 4'select PROCESS_INST_ID , max(case when rn = 1 then ACTIVITY_ID else null end), max(case when rn = 1 then ACTIVITY_NAME else null end), max(case when rn = 2 then ACTIVITY_ID else null end), max(case when rn = 2 then ACTIVITY_NAME else null end)from(select t.rn,t.PROCESS_INST_ID,r.ACTIVITY_ID,r.ACTIVITY_NAMEfrom (select row_number() over (partition by PROCESS_INST_ID order by ACTIVITY_INST_ID desc) as rn, ACTIVITY_INST_ID,ACTIVITY_ID,PROCESS_INST_ID from @t ) tinner join @r r on t.ACTIVITY_ID = r.ACTIVITY_IDand t.rn < 3) t1group by PROCESS_INST_ID |
 |
|
|
|
|
|
|
|