Calculating Age median from list of Dates of Birth

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • romanisa
    New Member
    • Feb 2008
    • 2

    Calculating Age median from list of Dates of Birth

    Hii friends

    I need to calculate the age median from the given dates of birth in an employee database in MS SQl.

    Please help...

    Roma
  • Delerna
    Recognized Expert Top Contributor
    • Jan 2008
    • 1134

    #2
    do a datediff between the current date and their birth date
    then take the average
    for example in months it is
    Code:
    SELECT avg(datediff(m,getdate(),birthdate))
    FROM employees
    is that what you mean

    Comment

    • deepuv04
      Recognized Expert New Member
      • Nov 2007
      • 227

      #3
      Originally posted by romanisa
      Hii friends

      I need to calculate the age median from the given dates of birth in an employee database in MS SQl.

      Please help...

      Roma

      Hi,


      for calculating the age use the following sample query and change it according to your requirement


      DECLARE @FromDate DATETIME,
      @ToDate DATETIME

      SELECT @FromDate = '1983-07-04',@ToDate = '2008-07-04'

      SELECT CASE WHEN @FromDate > @ToDate THEN NULL
      WHEN DATEPART(day, @FromDate) > DATEPART(day, @ToDate) THEN DATEDIFF(month, @FromDate, @ToDate) - 1
      ELSE DATEDIFF(month, @FromDate, @ToDate)
      END / 12.0


      thanks

      Comment

      • deepuv04
        Recognized Expert New Member
        • Nov 2007
        • 227

        #4
        Originally posted by Delerna
        do a datediff between the current date and their birth date
        then take the average
        for example in months it is
        Code:
        SELECT avg(datediff(m,getdate(),birthdate))
        FROM employees
        is that what you mean

        Hi,

        if the birth date is 2007-01-31 and today is 2008-02-01 and
        in the code SELECT avg(datediff(m, getdate(),birth date))
        FROM employees the function datediff(m,getd ate(),birthdate ) will give you the difference as 1 month though it is differ by 1 day.

        Comment

        • Delerna
          Recognized Expert Top Contributor
          • Jan 2008
          • 1134

          #5
          Originally posted by deepuv04
          Hi,

          if the birth date is 2007-01-31 and today is 2008-02-01 and
          in the code SELECT avg(datediff(m, getdate(),birth date))
          FROM employees the function datediff(m,getd ate(),birthdate ) will give you the difference as 1 month though it is differ by 1 day.

          Then use days
          avg(datediff(d, getdate(),birth date))

          Comment

          • romanisa
            New Member
            • Feb 2008
            • 2

            #6
            Hey Thanks everyone for the code....

            Comment

            Working...