
sqlserver 如何求出分组后每组的第一行
展开全部
SQL2005写法。
例如求出每个部门最高薪酬的人员信息。跟你每组第一行的要求很类似吧!
Declare @Employee table (ID int ,Dept int ,Salary decimal(10,2))
insert into @Employee values(1,10,5500.00)
insert into @Employee values(2,10,4500.00)
insert into @Employee values(3,20,1900.00)
insert into @Employee values(4,20,4800.00)
insert into @Employee values(5,40,6500.00)
insert into @Employee values(6,40,14500.00)
insert into @Employee values(7,40,44500.00)
insert into @Employee values(8,50,6500.00)
insert into @Employee values(9,50,7500.00)
--SELECT * FROM @Employee
SELECT
ID,Dept,Salary
FROM
(
SELECT
ROW_NUMBER() OVER (partition by Dept ORDER BY Salary desc) as Rank,
ID,Dept,Salary
FROM @Employee
) M
WHERE Rank=1
-----
执行结果:
---------
1 10 5500.00
4 20 4800.00
7 40 44500.00
9 50 7500.00
例如求出每个部门最高薪酬的人员信息。跟你每组第一行的要求很类似吧!
Declare @Employee table (ID int ,Dept int ,Salary decimal(10,2))
insert into @Employee values(1,10,5500.00)
insert into @Employee values(2,10,4500.00)
insert into @Employee values(3,20,1900.00)
insert into @Employee values(4,20,4800.00)
insert into @Employee values(5,40,6500.00)
insert into @Employee values(6,40,14500.00)
insert into @Employee values(7,40,44500.00)
insert into @Employee values(8,50,6500.00)
insert into @Employee values(9,50,7500.00)
--SELECT * FROM @Employee
SELECT
ID,Dept,Salary
FROM
(
SELECT
ROW_NUMBER() OVER (partition by Dept ORDER BY Salary desc) as Rank,
ID,Dept,Salary
FROM @Employee
) M
WHERE Rank=1
-----
执行结果:
---------
1 10 5500.00
4 20 4800.00
7 40 44500.00
9 50 7500.00
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询