我有一个带有两个字段的表"T_Person“,我想通过Height int, BirthDate datetime来搜索它。
当我查询这个表时,我希望得到的行的值与我搜索的值接近。例如,当我搜索身高为175厘米的人时,如下所示:
Select *
from T_Person
where Height = 175我还希望得到高度值接近175的行。例如174,173,176...
date列也是如此。当我搜索'2003-06-25‘时,我也希望得到与其相近的日期。
有可能吗?
发布于 2015-07-05 21:12:39
更改过滤器:
Select * from T_Person where Height >= 173 and Height <= 177或者:
Select * from T_Person where Height between 173 and 177对于datetime字段,您应该使用cast()函数来获得最佳结果:
Select * from T_Person where BirthDate
between CAST('2014-02-28' AS DATETIME) and CAST('2015-02-28' AS DATETIME); 发布于 2015-07-05 21:15:48
你需要某种度量来衡量是什么构成了接近。我还怀疑您希望完全匹配的内容最先出现。因此,要按“邻近度”对行进行排序,请使用:
select p.*
from t_person p
order by abs(height - 175);过滤结果非常有用,因此您还可以添加where子句:
select p.*
from t_person p
where height between 175 - 2 and 175 + 2
order by abs(height - 175);同样的想法也适用于日期。但是,您没有在问题中指定您的数据库,而日期函数是高度特定于数据库的。
发布于 2015-07-05 21:15:54
将175替换为所需的值。使用这个
Select * from T_Person where Height between 175 - 2 and 175 + 1https://stackoverflow.com/questions/31230684
复制相似问题