我有一个这样的sql表,
SomeDouble SomeInt
1.00 121
1.50 124
2.00 200
2.50 321
以此类推。最多10,000个SomeDouble
现在我可以有一个介于0.0到10,000.00之间的十进制数,我需要为它找到正确的行。例如,如果number是1.12,那么我希望它返回121。
1.49应该返回121,1.50应该返回124,1.51应该返回124。
我尝试的修剪版本是,
var myValue = 1.12
var SomeInt = (from mainTable in table1
join table3 in table2 on mainTable.someId equals table3.someId
where table3.Column1 == Column1 && mainTable.SomeDouble >= myValue
select mainTable.SomeInt).FirstOrDefault();
但我的输出是124。如何更改上面的内容,以获得最接近的最小数字,然后是myValue?
发布于 2019-05-23 08:45:02
因为SomeDouble
值是整数和半整数,所以可以将myValue
向上舍入到0.5的下一个倍数:
var myValueToLookUp = Math.Ceiling(myValue * 2) / 2;
然后使用mainTable.SomeDouble == myValueToLookUp
直接查找SomeInt
的值,以避免与<=或>=混淆或效率低下。
发布于 2019-05-22 13:15:41
在SQL中,您可以将最接近的表达式表示为:
select t.*
from t
order by abs(SomeDouble - 1.12)
fetch first 1 row only;
一种更有效的方法是首先将其范围缩小到两行:
select t.*
from ((select t.*
from t
where t <= 1.12
order by SomeDouble desc
fetch first 1 row only
) union all
((select t.*
from t
where t > 1.12
order by SomeDouble asc
fetch first 1 row only
)
) t
order by (SomeDouble - 1.12)
fetch first 1 row only;
发布于 2019-05-22 13:29:04
使用Linq查询:
var above = (from mainTable in table1
join table3 in table2 on mainTable.someId equals table3.someId
where table3.Column1 == Column1 && mainTable.SomeDouble >= myValue
orderby mainTable.SomeDouble
select new {SomeInt = mainTable.SomeInt, SomeDouble = mainTable.SomeDouble}).FirstOrDefault();
var below = (from mainTable in table1
join table3 in table2 on mainTable.someId equals table3.someId
where table3.Column1 == Column1 && mainTable.SomeDouble < myValue
orderby mainTable.SomeDouble descending
select new {SomeInt = mainTable.SomeInt, SomeDouble = mainTable.SomeDouble}).FirstOrDefault();
int SomeInt;
if (above == null)
SomeInt = below.SomeInt;
else if (below == null)
SomeInt = above.SomeInt;
else if (Math.Abs(below.SomeDouble - myValue) <= Math.Abs(above.SomeDouble - myValue))
SomeInt = below.SomeInt;
else
SomeInt = above.SomeInt;
https://stackoverflow.com/questions/56257706
复制