rahularyansharma
rahularyansharma

Reputation: 10755

join with rows only which have maximum sequence number

declare @emp table
(
  EmployeeId int, CompanyId int ,FirstName nvarchar(50),MiddleName nvarchar(50) ,LastName  nvarchar(50)
)

insert into @emp select 1,1,'rahul','kumar','Sharma'
insert into @emp select 16,1,'nitin','','Sharma'

select * From @emp

declare @PayInformation table
(
  EmployeeId int ,IsHourly bit ,PayFrequency nvarchar(50) ,Amount decimal(18,2),StandardHours decimal(18,2)  ,Year int,Sequence int
)


 insert into @PayInformation select 1,0,'monthly',40.00,40,2013,1
 insert into @PayInformation select 1,0,'monthly',100.00,40,2013,2
 insert into @PayInformation select 16,0,'monthly',100.00,40,2013,2

 select * From @PayInformation

 select * from @emp as e 
 inner join @PayInformation as p ON e.EmployeeId=p.EmployeeId

This join statement give me 3 rows , as EmployeeId 1 have 2 rows in PayInformation table. but i want to join the with only rows which have maximum sequence number. so as per my desired result it should join with the sequence no 2 for employee 1 .

Upvotes: 2

Views: 581

Answers (1)

roman
roman

Reputation: 117380

there're several ways to do that

First:

select * 
from @emp as e 
    outer apply (
        select top 1 t.*
        from @PayInformation as t
        where t.EmployeeId=e.EmployeeId
        order by t.Sequence desc
    ) as p

Second:

select * 
from @emp as e 
    left outer join @PayInformation as p on p.EmployeeId=e.EmployeeId
where
    exists (
        select 1
        from @PayInformation as t
        where t.EmployeeId=e.EmployeeId
        having max(t.Sequence) = p.Sequence
   )

Third

;with cte_PayInformation as (
    select *, row_number() over(partition by EmployeeId order by Sequence desc) as rn
    from @PayInformation
)
select * 
from @emp as e 
    left outer join cte_PayInformation as p on p.EmployeeId = e.EmployeeId and p.rn = 1

sql fiddle demo

Just quick note - these queries are not equivalent, second one could return more rows if you have duplicate Sequence, EmployeeId in @PayInformation table.

Upvotes: 2

Related Questions