SQL Server:获取具有附加数据的一系列值之间的最大值
Posted
技术标签:
【中文标题】SQL Server:获取具有附加数据的一系列值之间的最大值【英文标题】:SQL Server: get max value between a range of values with additional data 【发布时间】:2016-12-07 00:32:35 【问题描述】:大多数人想要最大值,但我需要一个范围内的最大值加上额外的数据。例如,我有一个团队及其经理及其经理 ID 的列表。我查看了谷歌/***,但大多数人只想要最大值,但我也需要额外的列,这就是我问这个问题的原因。
表 1:
team mgr_level mgr_id
-----------------------
aa 1 111
aa 2 222
aa 3 333
bb 1 111
bb 2 222
cc 1 111
cc 2 222
cc 3 444
cc 4 888
表2:
employee emp_id team
------------------------------
smith, mary 23 aa
jones, john 34 bb
ramjet, roger 98 cc
james, adam 111 mgr_team
green, rachel 222 mgr_team
bruin, breezly 333 mgr_team
runner, road 444 mgr_team
potter, harry 888 mgr_team
我需要选择介于 222 和 444 之间的最大值(mgr_id)以及其他数据(团队和 mgr_id)。
需要的结果如下所示。有没有办法一步完成而不是两步?
name team primary_mgr_id manager_name
-----------------------------------------------
smith, mary aa 333 bruin, breezly
jones, john bb 222 green, rachel
ramjet, roger cc 444 runner, road
我试过了,但 SQL Server 不断为每个名称返回多行:我做错了什么?
select max(mgr_id) as [primary_mgr_id], t2.employee, t1.mgr_id
from table2 t2
inner join table1 t1 on t2.team = t2.team
group by t2.employee, t1.mgr_id
感谢您的帮助。 斯文
【问题讨论】:
我添加了它!谢谢我忘了添加它 【参考方案1】:一个选项是借助 Row_Number()
Select Name = A.Employee
,A.Team
,primary_mgr_id = B.Mgr_ID
,manager_name = B.manager_name
From Table2 A
Join (
Select A.*
,manager_name = employee
,RN = Row_Number() over (Partition By A.Team Order by A.mgr_level desc)
From Table1 A
Join Table2 B on (A.Mgr_ID=B.Emp_ID)
Where mgr_id between 222 and 444
) B on A.Team=B.Team and B.RN=1
返回
Name Team primary_mgr_id manager_name
smith, mary aa 333 bruin, breezly
jones, john bb 222 green, rachel
ramjet, roger cc 444 runner, road
另一种选择是使用交叉应用
Select Name = A.Employee
,A.Team
,primary_mgr_id = B.Mgr_ID
,manager_name = B.employee
From Table2 A
Cross Apply (
Select Top 1 C.*,D.employee
From Table1 C
Join Table2 D on (emp_id = mgr_id)
where C.Team=A.Team and mgr_id between 222 and 444 Order by mgr_level desc
) B
【讨论】:
【参考方案2】:这是你要找的那个吗?
SELECT
employee AS name, team, max_mgr_id AS primary_mgr_id, t3.employee as manager_name
FROM
table2 t2
JOIN (
SELECT team, MAX(mgr_id) AS max_mgr_id
FROM table1
) t1 ON t2.team = t1.team
JOIN table2 t3 ON t3.emp_id = t1.max_mgr_id AND t3.team = 'mgr_team'
【讨论】:
【参考方案3】:我会像使用 outer apply
那样做这个
select t2.*, t1.mgr_id as primary_mgr_id , t1.name as manager_name
from table2 t2 outer apply
(select t1.mgr_id, tt2.name
from table1 t1 join
table2 tt2
on t1.mgr_id = tt2.emp_id
where t1.team = t2.team and
t1.mgr_id between 222 and 444
order by t1.mgr_id desc
) t1;
【讨论】:
以上是关于SQL Server:获取具有附加数据的一系列值之间的最大值的主要内容,如果未能解决你的问题,请参考以下文章
是否可以利用 SQL Server 数据库项目来管理一组具有各种架构差异的数据库?
SQL Server附加数据库失败:无法打开物理文件,操作系统错误5:拒绝访问”解决方法