Select Between 17:00 Yesterday and 17:00 Today

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    Select Between 17:00 Yesterday and 17:00 Today

    I can get the whole of yesterday and today using this query
    Code:
    SELECT site, ord_date,
    LEFT(RTRIM(LTRIM(descr)),24) account
    FROM orders
    WHERE ord_date BETWEEN 
    CAST(CAST(DATEADD(DAY,-1,GETDATE()) AS INT) AS DATETIME)
     AND 
    CAST(GETDATE() AS DATETIME)
    Casting GETDATE to INT truncates the time element and casting back to DATETIME resets the time element to midnight.
    I figured if I did something like this it would give me 17:00 yesterday
    Code:
    CAST(CAST(DATEADD(DAY,-1,GETDATE()) AS INT)+' 17:00:00.000' AS DATETIME)
    But error:
    Syntax error converting the varchar value ' 17:00:00.000' to a column of data type int.
    I must be close.
    Any help appreciated
  • ck9663
    Recognized Expert Specialist
    • Jun 2007
    • 2878

    #2
    Here, read some of this...

    Happy Coding!!!

    ~ CK

    Comment

    • code green
      Recognized Expert Top Contributor
      • Mar 2007
      • 1726

      #3
      Here, read some of this
      That doesn't teach me anything.
      String literals are used for the dates throughout.
      Or did I miss something?

      Comment

      • reachenbee
        New Member
        • Jan 2010
        • 1

        #4
        Please try this.

        DATEADD( HH, 17, CAST(CAST(DATEA DD(DAY,-1,GETDATE()) AS INT) AS DATETIME))

        -bala

        Comment

        • code green
          Recognized Expert Top Contributor
          • Mar 2007
          • 1726

          #5
          Code:
          DATEADD( HH, 17, CAST(CAST(DATEADD(DAY,-1,GETDATE()) AS INT) AS DATETIME))
          Good Thinking! Add 17 hours to midnight. Wow. I'll try that. Thanks.

          Comment

          • code green
            Recognized Expert Top Contributor
            • Mar 2007
            • 1726

            #6
            Just an update for anybody interested.
            CAST ...TO INT is unreliable.
            It can flip a day either way, probably something to do with rounding.
            CONVERT to a date works better. then CAST back to DATETIME to get midnight.
            And simply DATEADD any number of hours you like
            Code:
            DATEADD(HH,17,CAST(CONVERT(VARCHAR,DATEADD(
                 DAY,-1,GETDATE()) ,23) AS DATETIME)) yesterday1700

            Comment

            Working...