By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,378 Members | 1,373 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,378 IT Pros & Developers. It's quick & easy.

Selecting From Multiple Time Periods

P: 1
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
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 1,134
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

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

Expert 2.5K+
P: 2,878
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.