469,343 Members | 5,620 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,343 developers. It's quick & easy.

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.
Apr 11 '08 #1
2 1636
Delerna
1,134 Expert 1GB
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
Expand|Select|Wrap|Line Numbers
  1. select DateTime,FieldValue
  2. FROM
  3. (   select DateTime,
  4.          (datepart(hh,datetime)*1.0)+(datepart(mi,DateTime)/100.0) as T,
  5.          FieldValue,
  6.          datepart(dw,DateTime)as d 
  7.     from YourTable
  8. )a
  9. WHERE (d=1 or d=7 or T>=21.3 or T<=8.3) and Month(DateTime)=1
  10.  

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.
Apr 11 '08 #2
ck9663
2,878 Expert 2GB
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:

Expand|Select|Wrap|Line Numbers
  1. where  datename(dw,YourDateField) in ('Saturday', 'Sunday') 

-- CK
Apr 12 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Manu | last post: by
2 posts views Thread by Alphonse Giambrone | last post: by
1 post views Thread by Bob Loveshade | last post: by
2 posts views Thread by areef.islam | last post: by
3 posts views Thread by D. Yates | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.