查询工资排第X的人

员工表(Employee)
字段名 描述 数据类型 备注
EmpNum 工号 Char(5),如e0001 主键
EmpName 姓名 Nvarchar(20)

工资表(Wage)
字段名 描述 数据类型 备注
WageNo 编号 int 主键,自动增长列
amount 工资金额 money 必须大于0

出勤表(Attender)
字段名 描述 数据类型 备注
id 编号 int 主键,自动增长列
EmpNum 工号 char 与Employee表工号关联(外键)
WNum 工资编号 int 与Wage表编号关联(外键)

--查询工资第X(如倒数第3的)高的员工信息与其工资

作者: zhouderek   发布时间: 2011-01-13

SQL code
if OBJECT_ID('Employee')is not null drop table Employee
go
if OBJECT_ID('Wage')is not null drop table Wage
go
if OBJECT_ID('Attender')is not null drop table Attender
go
create table Employee
(
  EmpNum  char(5),
  EmpName  varchar(20)
)
insert into Employee
select 'E001','AAA' UNION ALL
select 'E002','BBB' 
create table Wage
(
   WageNo  int identity,
   amount money check(amount>0)
)
insert into Wage
select 2000 union all
select 1800

create table Attender
(
   id int identity,
   EmpNum char(5),
   WNum int
)
insert into Attender
select 'E001',1 union all
select 'E002',2 

declare @n int
declare @s varchar(10)
set @s='asc' --倒数第一  --desc第一
set @n=1 --排名第一
exec ('
select EmpName,amount
from( 
select ROW_NUMBER()over(order by amount '+@s+')as rn,EmpName,amount
from Employee e join Attender a on a.EmpNum=e.EmpNum join Wage w on a.WNum=w.WageNo) tt
where rn='+@n+'
')

作者: Dlut_LIuQ   发布时间: 2011-01-13