0

How can I select data from a table based on weekday or weekend, like if date is a weekday then select only historical weekday data from the table & if date is a weekend then select only historical weekend data.

I have tried to do that in this way but no luck

DECLARE @MyDate DATE = '08/17/2013'

SELECT datename(dw,@MyDate)

SELECT * FROM MyTable
WHERE 
datename(dw,DateColumnInTable) IN ( 
CASE WHEN (datename(dw,@MyDate) IN ('Saturday','Sunday')) THEN '''Saturday'',''Sunday'''
ELSE  'Monday'',''Tuesday'',''Wednesday'',''Thursday'',''Friday'
END )

Any I can see lots of data in my table for saturday and sunday but this query is giving me blank record set.

Zerotoinfinity
  • 6,290
  • 32
  • 130
  • 206
  • Why down vote? I tried first then I did google about it, after that I search SO and my question is not subjective. Where I am wrong ? – Zerotoinfinity Aug 20 '13 at 15:51

1 Answers1

1

Here's one way:

DECLARE @MyDate DATE = '08/17/2013'

IF (DATEPART(weekday, @MyDate) IN (1,7))
    SELECT * 
    FROM MyTable
    WHERE DATEPART(weekday, DateColumnInTable) IN (1,7)
ELSE
    SELECT * 
    FROM MyTable
    WHERE DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6

If you would like to do it in one clause you can do something like the following, but it may perform worse:

SELECT *
FROM MyTable
WHERE (DATEPART(weekday, @MyDate) IN (1,7) AND DATEPART(weekday, DateColumnInTable) IN (1,7))
OR (DATEPART(weekday, @MyDate) BETWEEN 2 AND 6 AND DATEPART(weekday, DateColumnInTable) BETWEEN 2 AND 6)
lc.
  • 113,939
  • 20
  • 158
  • 187