如何解决获取特定列sql服务器的分组和聚合最小值的ID
如何根据下表获取最接近的业务分支
BranchId BusinessId Distance
-- --- ---
24 267 221.71464641964
13 258 253.099943313603
14 258 253.099943313603
15 258 17.3790669756556
17 260 3456.74117699001
32 260 9.852770682035
121 260 374.907804283969
122 260 374.907804283969
127 260 213.074377898838
63 292 18.6199088005564
64 292 9.35737878020064
65 292 3456.74117699001
所以结果会是这样
BranchId BusinessId Distance
-- --- ---
24 267 221.71464641964
15 258 17.3790669756556
32 260 9.852770682035
64 292 9.35737878020064
解决方法
您可以使用窗口功能:
select distinct
first_value(BranchId) over (partition by BusinessId order by Distance) BranchId,BusinessId,min(Distance) over (partition by BusinessId) Distance
from tablename
请参见demo。
结果:
> BranchId | BusinessId | Distance
> -------: | ---------: | ---------------:
> 15 | 258 | 17.3790669756556
> 24 | 267 | 221.71464641964
> 32 | 260 | 9.852770682035
> 64 | 292 | 9.35737878020064
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。