1
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

この結合ステートメントはEmployeeId、テーブルに2行あるため、3行になりPayInformationます。しかし、最大のシーケンス番号を持つ行のみを結合したいです。したがって、私の望ましい結果に従って、従業員 1 のシーケンス番号 2 と結合する必要があります。

4

1 に答える 1

1

それにはいくつかの方法があります

初め:

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

2番:

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
   )

三番

;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

簡単に注意してください - これらのクエリは同等ではありません.テーブルに重複Sequence, EmployeeIdがある場合、2番目のクエリはより多くの行を返す可能性があります.@PayInformation

于 2013-10-23T10:06:10.753 に答える