Selecting From Multiple Time Periods

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • descarre
    New Member
    • Apr 2008
    • 1

    #1

    Selecting From Multiple Time Periods

    I greatly appreciate your help as I have been trying to come up with the correct sql statement but output is inaccurate. How do you write the correct t-sql statement for the following:

    SELECT FieldValue WHERE DateTime is from 9:30PM - 8:30AM on Mondays thru Fridays, AND ALL-DAY (i.e. all DateTime values) on Saturdays & Sundays for the whole month of January 2008.

    I am using SQL Server 2000. Thank you.
  • Delerna
    Recognized Expert Top Contributor
    • Jan 2008
    • 1134

    #2
    Hi Descarre and welcome

    First, here are a few facts that we can use to achieve a solution
    1) DatePart is a function that can be used to find out all sorts of info about a datetime value
    2) The WeekDay number for saturday and sunday are 7 and 1 respectively
    so we can use that to return all of the records for those days.
    3) The Hour part + (the minute part/100) will give us a decimal number
    we can use that to return the data between the times you want
    4) The Month function returns the month number
    we can use that to return the data for a particular month

    Using those facts, here is one way of achieving what you want
    [code=sql]
    select DateTime,FieldV alue
    FROM
    ( select DateTime,
    (datepart(hh,da tetime)*1.0)+(d atepart(mi,Date Time)/100.0) as T,
    FieldValue,
    datepart(dw,Dat eTime)as d
    from YourTable
    )a
    WHERE (d=1 or d=7 or T>=21.3 or T<=8.3) and Month(DateTime) =1
    [/code]


    Oh, by the way, I don't think its a good idea to name a field the same as a data type. It might be a little confusing if you need to debug your query in 6 months time.

    Comment

    • ck9663
      Recognized Expert Specialist
      • Jun 2007
      • 2878

      #3
      I think the weekday number may be affected by setting the first day of the week server setting. You may also use the datename function and just check the string names of the day. Something like:

      Code:
      where  datename(dw,YourDateField) in ('Saturday', 'Sunday')

      -- CK

      Comment

      Working...