TSQL JOIN澄清

时间:2010-09-20 09:21:53

标签: sql-server tsql

假设我有两张桌子

declare @emp table
(
  EmpID int,
  EmpName varchar(10)

)

declare @Remu table
(
   EmpID int,
   Sal Decimal(10,2),
   PaidYear varchar(10)
)

我希望在PaidYear(With Ties)上分组最高工资

预期的输出

EmpID EmpName PaidYear Sal 
1     Jon     2001     2000
2     Smith   2001     2000

3     Nash   2003      4000     
4     Hoge   2005      5000
5     Peter  2005      5000

使用Join

时出现问题
select e.EmpID,e.EmpName,r.Sal,r.PaidYear from @emp e
inner join
(select max(Sal) as Sal,PaidYear from @Remu group by PaidYear)r
on e.EmpID=???

当我在

中选择EmpID时
select max(Sal) as Sal,PaidYear from @Remu group by PaidYear

我必须按照PaidYear和EmpID进行分组,这不会像我预期的那样提供所需的结果。

如何解决这个问题。我想要一个与SQL Server 2000兼容的查询。

2 个答案:

答案 0 :(得分:1)

select e.EmpID,e.EmpName,r.Sal,r.PaidYear
from @emp e inner join @Remu r on e.EmpId = r.EmpId
where r.sal in (select max(sal) from @remu group by paidyear)

答案 1 :(得分:0)

每年需要确定特定于该年度的单一最高工资。

select e.EmpID
    , e.EmpName
    , r.Sal
    , r.PaidYear 
from @emp as e 
inner join @Remu as r 
on e.EmpId = r.EmpId 
where r.sal = (select max(sal) 
               from @remu 
               where paidyear = r.PaidYear ' makes it year specific
              ) 

要测试的数据:

declare @emp table 
( 
  EmpID int, 
  EmpName varchar(10) 

) 

declare @Remu table 
( 
   EmpID int, 
   Sal Decimal(10,2), 
   PaidYear varchar(10) 
) 

insert into @emp (EmpID, EmpName)
values(1, 'Jon')
insert into @emp (EmpID, EmpName)
values(2, 'Smith')
insert into @emp (EmpID, EmpName)
values(3, 'Nash')
insert into @emp (EmpID, EmpName)
values(4, 'Hoge')
insert into @emp (EmpID, EmpName)
values(5, 'Peter')

Insert into @Remu (EmpID, Sal, PaidYear)
values(1, 2000, '2001')

Insert into @Remu (EmpID, Sal, PaidYear)
values(2, 4999, '2001') 

Insert into @Remu (EmpID, Sal, PaidYear)
values(2, 8000, '2003') 

Insert into @Remu (EmpID, Sal, PaidYear)
values(3,4000, '2003')      

Insert into @Remu (EmpID, Sal, PaidYear)
values(4, 5000, '2005')      

Insert into @Remu (EmpID, Sal, PaidYear)
values(5, 4999, '2005')

结果:

EmpID   EmpName Sal    PaidYear
4           Hoge    5000.00    2005
2           Smith   8000.00    2003
2           Smith   4999.00    2001