Near Number Function

  • Hi,

    I have a table called EmpAges with 2 fields: Name & Age. I want to know if there is a way to get all the employees near an age. For example if my value is 20 then I want all the people near the age of 20 first then the people age 19, then 20, then 18, then 22 and so on.

    Does SQL Server have a function that would allow such a query?

    Thanks,

    Bob

  • First you should be keeping the date of birth instead of the age.

    2nd :

    Select whatever from dbo.Employees where ABS(@WantedAge - Age) = @MaxAgeDifference

    order by ABS(@WantedAge - Age), Age, Name

  • It seems like what you are looking for is a fuzzy search on top of an order by that is not supported.

    you can try something like:

    insert into #EmpAges (Name, Age)

    select 'Abraham', 18 union

    select 'Reginald', 17 union

    select 'Cheryl', 16 union

    select 'Michel', 19 union

    select 'Innes', 20 union

    select 'Ann', 21 union

    select 'Marjorie', 22 union

    select 'Morningstar', 23 union

    select 'Burt', 24 union

    select 'Sheryl', 19 union

    select 'Livia', 18 union

    select 'Charlene', 17 union

    select 'Stearns', 16 union

    select 'Heather', 19 union

    select 'Michael', 20 union

    select 'Sylvia', 21 union

    select 'Albert', 22 union

    select 'Anne', 23 union

    select 'Meander', 24 union

    select 'Dean', 19 union

    select 'Dirk', 18 union

    select 'Johnson', 20 union

    select 'Akiko', 21

    Declare @Age smallint

    Declare @Diff tinyint

    set @Age = 20

    set @Diff = 2

    select *

    from #EmpAges

    where age between (@age - @Diff) and (@age + @Diff)

    But I don't see a way to order it the way you want

  • Yeah I still type fast, don't mention it . Not sure that this is exactly what's needed but I guess we'll know soon.

  • But I don't see a way to order it the way you want

    select *

    from #EmpAges

    where age between (@age - @Diff) and (@age + @Diff)

    order by abs(age - @age) , age


    * Noel

  • The ABS Function did the trick. Thanks Guys!!!

  • HTH.

  • So you agree with me now. Just wondering if the (age - @Diff) and (age + @Diff) version is sargable (since you both used it).

Viewing 8 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply