Get the closest date

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Benny Chow

    Get the closest date

    Hello,

    I need help in writing a SQL statement in MS SQL Server 2000 to select
    the latest date (i.e., the date closest to or equal to the current date)
    for a given date.

    For example, in a table I have the following records:
    Date Exchange-Rate
    01/Sep/03 0.55
    05/Sep/03 0.59

    If the given date is 02/Sep/03, then the rate 0.55 should be return.
    If the given date is 03/Sep/03, then the rate 0.55 should be return.
    If the given date is 04/Sep/03, then the rate 0.59 should be return.

    Thanks in advanced,

    Benny

    *** Sent via Developersdex http://www.developersdex.com ***
    Don't just participate in USENET...get rewarded for it!
  • Erland Sommarskog

    #2
    Re: Get the closest date

    Benny Chow (benny@stg.net. nz) writes:[color=blue]
    > I need help in writing a SQL statement in MS SQL Server 2000 to select
    > the latest date (i.e., the date closest to or equal to the current date)
    > for a given date.
    >
    > For example, in a table I have the following records:
    > Date Exchange-Rate
    > 01/Sep/03 0.55
    > 05/Sep/03 0.59
    >
    > If the given date is 02/Sep/03, then the rate 0.55 should be return.
    > If the given date is 03/Sep/03, then the rate 0.55 should be return.
    > If the given date is 04/Sep/03, then the rate 0.59 should be return.[/color]

    Next time, please include CREATE TABLE statements for the tables you
    are working with and INSERT statements with sample data. This makes it
    possible to post a tested solution.

    Thus, this solution is untested:

    SELECT exchangerage, date
    FROM rates
    WHERE date = (SELECT MAX(date)
    FROM rates
    WHERE date <= @date)



    --
    Erland Sommarskog, SQL Server MVP, sommar@algonet. se

    Books Online for SQL Server SP3 at
    SQL Server 2025 redefines what's possible for enterprise data. With developer-first features and integration with analytics and AI models, SQL Server 2025 accelerates AI innovation using the data you already have.

    Comment

    • David Portas

      #3
      Re: Get the closest date

      CREATE TABLE ExchangeRates (rdate DATETIME PRIMARY KEY, exchangerate
      DECIMAL(10,2) NOT NULL)
      INSERT INTO ExchangeRates VALUES ('20030901',0.5 5)
      INSERT INTO ExchangeRates VALUES ('20030905',0.5 9)

      DECLARE @dt DATETIME
      SET @dt = '20030902'

      Here's one method:

      SELECT exchangerate
      FROM ExchangeRates
      WHERE rdate =
      (SELECT MIN(rdate)
      FROM ExchangeRates
      WHERE ABS(DATEDIFF(DA Y,@dt,rdate))=
      (SELECT MIN(ABS(DATEDIF F(DAY,@dt,rdate )))
      FROM ExchangeRates))

      Or you can use TOP:

      SELECT TOP 1 exchangerate
      FROM ExchangeRates
      ORDER BY ABS(DATEDIFF(DA Y,@dt,rdate)), rdate

      Personally, I would avoid TOP because it's a MS proprietary extension to
      SQL.

      --
      David Portas
      ------------
      Please reply only to the newsgroup
      --


      Comment

      • David Portas

        #4
        Re: Get the closest date

        Benny wants the closest, before or after the specified date according to his
        example.

        --
        David Portas
        ------------
        Please reply only to the newsgroup
        --


        Comment

        • Benny Chow

          #5
          Re: Get the closest date

          Thanks David, this is exactly what I needed. :)

          *** Sent via Developersdex http://www.developersdex.com ***
          Don't just participate in USENET...get rewarded for it!

          Comment

          • Steve Kass

            #6
            Re: Get the closest date

            Benny,

            This might be a little more efficient than other
            solutions, but it's not as simple:



            select top 1 exchangerate
            from (
            select exchangerate, pref
            from (
            select top 1 exchangerate, 1 as pref
            from (
            select top 3 rdate, exchangerate
            from ExchangeRates E1
            where E1.rdate >= (
            select max(rdate) as lastBefore
            from ExchangeRates E2
            where E2.rdate < @dt
            )
            order by rdate
            ) X
            order by case when rdate < @dt then @dt - rdate else rdate - @dt end
            ) X1
            union all
            select exchangerate, pref
            from (
            select top 1 exchangerate, 2 pref
            from ExchangeRates
            order by rdate
            ) Y
            ) T
            order by pref

            -- Steve Kass
            -- Drew University
            -- Ref: 250CBB08-57AE-45C7-97F2-AF26AFC368ED

            Benny Chow wrote:[color=blue]
            > Hello,
            >
            > I need help in writing a SQL statement in MS SQL Server 2000 to select
            > the latest date (i.e., the date closest to or equal to the current date)
            > for a given date.
            >
            > For example, in a table I have the following records:
            > Date Exchange-Rate
            > 01/Sep/03 0.55
            > 05/Sep/03 0.59
            >
            > If the given date is 02/Sep/03, then the rate 0.55 should be return.
            > If the given date is 03/Sep/03, then the rate 0.55 should be return.
            > If the given date is 04/Sep/03, then the rate 0.59 should be return.
            >
            > Thanks in advanced,
            >
            > Benny
            >
            > *** Sent via Developersdex http://www.developersdex.com ***
            > Don't just participate in USENET...get rewarded for it![/color]

            Comment

            • Erland Sommarskog

              #7
              Re: Get the closest date

              David Portas (REMOVE_BEFORE_ REPLYING_dporta s@acm.org) writes:[color=blue]
              > Benny wants the closest, before or after the specified date according to
              > his example.[/color]

              Funny guy. :-) Some of our tables for prices and rates are sparse in a
              similar manner, but we always assume that a value applies until a new
              value comes in. So I assume he wanted the same.

              But had Benny included CREATE TABLE and sample data in INSERT statements,
              I would have seen that my solution was wrong!


              --
              Erland Sommarskog, SQL Server MVP, sommar@algonet. se

              Books Online for SQL Server SP3 at
              SQL Server 2025 redefines what's possible for enterprise data. With developer-first features and integration with analytics and AI models, SQL Server 2025 accelerates AI innovation using the data you already have.

              Comment

              • David Portas

                #8
                Re: Get the closest date

                > Funny guy. :-) Some of our tables for prices and rates are sparse in a[color=blue]
                > similar manner, but we always assume that a value applies until a new
                > value comes in. So I assume he wanted the same.[/color]

                I agree that it seems like an unusual requirement. Although I suppose if you
                wanted to calculate the value of a currency deal retrospectively it might
                make sense to take the closest rate as the best approximation. But IANAA.

                [color=blue]
                > But had Benny included CREATE TABLE and sample data in INSERT statements,
                > I would have seen that my solution was wrong![/color]

                I know that feeling! :|

                --
                David Portas
                ------------
                Please reply only to the newsgroup
                --


                Comment

                • Benny Chow

                  #9
                  Re: Get the closest date

                  Thanks for all your guys help ^^.

                  *** Sent via Developersdex http://www.developersdex.com ***
                  Don't just participate in USENET...get rewarded for it!

                  Comment

                  Working...