gpt4 book ai didi

SQL 服务器 : get max value between a range of values with additional data

转载 作者:行者123 更新时间:2023-12-04 22:09:02 24 4
gpt4 key购买 nike

大多数人都想要最大值,但我需要范围内的最大值加上额外的数据。例如,我有一个团队及其经理及其经理 ID 的列表。我查看了 google/stackoverflow,但大多数人只想要最大值,但我也需要额外的列,这就是我问这个问题的原因。

表 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

感谢您的帮助。斯文

最佳答案

One Option is with the help of a 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

Another Option is to use a CROSS APPLY

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

关于SQL 服务器 : get max value between a range of values with additional data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41007423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com