sql - SQL获取最接近数字的值
问题描述
我需要从 Quantity 列中找到 Divide 列中每个数字的最接近的值,并将在这两个 Quantities 的 Value 列中找到的值。
示例:在 Divide 列中,5166 的值将最接近 Quantity 列的值 5000。为了避免多次使用这两个值,我需要将 5000 的值放在两个数字的值列中,如下例所示。另外,是否可以在没有循环的情况下执行此操作?
Quantity Divide Rank Value
15500 5166 5 5000
1250 416 5 0
5000 1666 5 5000
12500 4166 4 0
164250 54750 3 0
5250 1750 3 0
6250 2083 3 0
12250 4083 3 0
1750 583 2 0
17000 5666 2 0
2500 833 2 0
11500 3833 2 0
1250 416 1 0
解决方案
这里有几个答案,但它们都使用 ctes/complex 子查询。有一种更简单/更快的方法,只需进行几次自我加入和分组
https://www.db-fiddle.com/f/rM268EYMWuK7yQT3gwSbGE/0
select
min(min.quantity) as minQuantityOverDivide
, t1.divide
, max(max.quantity) as maxQuantityUnderDivide
, case
when
(abs(t1.divide - coalesce(min(min.quantity),0))
<
abs(t1.divide - coalesce(max(max.quantity),0)))
then max(max.quantity)
else min(min.quantity) end as cloestQuantity
from t1
left join (select quantity from t1) min on min.quantity >= t1.divide
left join (select quantity from t1) max on max.quantity < t1.divide
group by
t1.divide
推荐阅读
- swiftui - 从 SwiftUI 中的后退按钮中删除文本
- php - 在循环中将更多数组混合在一起
- python - “后退”按钮在带有 Kivy 的 Python 中不起作用
- spring - 如何使用 swagger 和 openapi 公开 @GetMapping @RequestBody?
- python - RuntimeError: 'cx_Freeze.freezer.ConfigError: 找不到名为 numpy.core._methods 的文件/目录'
- c++ - Leetcode 28 - 实现 strStr():问题
- php - 将一个添加到 sql 列
- reactjs - 如何使用 React Hooks 更改按钮单击时的图像?
- python - 无法在没有 .NET Azure Python Function App v2 的情况下创建函数
- r - 数据框每一行的字符串的部分匹配