Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

Get particular day between two dates Expand / Collapse
Author
Message
Posted Friday, August 8, 2014 8:35 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Monday, November 24, 2014 7:37 AM
Points: 228, Visits: 568
Hi All,

I want to list Dates for particular day between two dates.


for eg. if user enters 08/01/2014 and 08/31/2014 with value 0 then all the Sundays and related dates should be display.

if above contamination with 1 then all Mondays,


Kindly help.



Thanks
Abhas
Post #1601210
Posted Friday, August 8, 2014 9:34 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Monday, November 24, 2014 7:37 AM
Points: 228, Visits: 568
Hi All,

I want to list Dates for particular day between two dates.


for eg. if user enters 08/01/2014 and 08/31/2014 with value 0 then all the Sundays and related dates should be display.

if above Combination with 1 then all Mondays date,


Kindly help.



Thanks
Abhas
Post #1601238
Posted Friday, August 8, 2014 9:56 AM
SSC Journeyman

SSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC Journeyman

Group: General Forum Members
Last Login: Wednesday, December 24, 2014 7:40 AM
Points: 89, Visits: 164
You can use a recursive common table expression to achieve this.

DECLARE @startDate DATETIME = '8/1/2014'
DECLARE @endDate DATETIME = '8/31/2014'
DECLARE @dayOfWeek INT = 1 -- 1=Sun, 7=Sat

;WITH cte_Recursion AS
(
SELECT @startDate AS [Date]
UNION ALL
SELECT DATEADD(DAY, 1, [Date])
FROM cte_Recursion
WHERE [Date] < @endDate
)
SELECT [Date]
FROM cte_Recursion
WHERE DATEPART(WEEKDAY, [Date]) = @dayOfWeek
OPTION (MAXRECURSION 0) -- MaxRecursion 0 is needed when dates are more than 100 days apart

Post #1601250
Posted Friday, August 8, 2014 10:14 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Wednesday, December 24, 2014 10:57 AM
Points: 10,387, Visits: 13,454
kherald provided a solution. Here's my take which still lets you use 0 for Sunday instead of 1 and also takes into account the Language setting of your SQL Server because some languages (actually most in the version of SQL Server I have installed) use Monday as day 1 not Sunday. You can combine both solutions to make it fit your purposes:

DECLARE @StartDate DATE = '2014-08-01', 
@EndDate DATE = '2014-08-31',
@DayNo TINYINT = 6;

/* this is a virtual numbers/tally table that is used to get all the days
between the days. If you already have a calendar table or a table that has
the dates you are querying this isn't necessary */
WITH nums
AS (
SELECT
ROW_NUMBER() OVER (ORDER BY (
SELECT
NULL
)) - 1 AS N
FROM
sys.all_columns AS AC
),
Calendar
AS (
SELECT
CONVERT(DATE, DATEADD(DAY, n, @StartDate)) AS theDate
FROM
nums
),
WeekDays
AS (
SELECT
*,
/* figure what day is the first day of the week. This setting is controlled by the
language of the SQL Server and you can see the values for DateFirst in sys.syslanguages */
CASE @@DateFirst
/* First day of week is monday (1) and last day of week is Sunday (7)*/
WHEN 1 THEN CASE DATEPART(WEEKDAY, theDate)
WHEN 7 THEN 0
ELSE DATEPART(WEEKDAY, theDate)
END
/* 1 and 7 are the only options for @@DATEFIRST currently so
Sunday is first day of week when @@DATEFIRS isn't 1 */
ELSE DATEPART(WEEKDAY, theDate) - 1
END AS DayNo,
DATENAME(WEEKDAY, theDate) AS DayName
FROM
Calendar
)
SELECT
*
FROM
WeekDays
WHERE
WeekDays.theDate BETWEEN @StartDate
AND @EndDate AND
WeekDays.DayNo = @DayNo;





Jack Corbett

Applications Developer

Don't let the good be the enemy of the best. -- Paul Fleming

Check out these links on how to get faster and more accurate answers:
Forum Etiquette: How to post data/code on a forum to get the best help
Need an Answer? Actually, No ... You Need a Question
How to Post Performance Problems
Crosstabs and Pivots or How to turn rows into columns Part 1
Crosstabs and Pivots or How to turn rows into columns Part 2
Post #1601257
Posted Friday, August 8, 2014 10:18 AM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 4:23 PM
Points: 35,821, Visits: 32,494
kherald69 (8/8/2014)
You can use a recursive common table expression to achieve this.

That's a recursive CTE that counts. Please see the following article for why that's a bad idea even for small date ranges.
http://www.sqlservercentral.com/articles/T-SQL/74118/


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1601260
Posted Friday, August 8, 2014 10:40 AM


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Wednesday, December 24, 2014 10:57 AM
Points: 10,387, Visits: 13,454
Jeff Moden (8/8/2014)
kherald69 (8/8/2014)
You can use a recursive common table expression to achieve this.

That's a recursive CTE that counts. Please see the following article for why that's a bad idea even for small date ranges.
http://www.sqlservercentral.com/articles/T-SQL/74118/


You can use the Itzik style cross join to replace reading sys.all_columns to get the numbers cte I created in my solution and get rid of all reads in my solution. Like this:

SET STATISTICS IO ON;
DECLARE
@StartDate DATE = '2014-08-01',
@EndDate DATE = '2014-08-31',
@DayNo TINYINT = 6;

/* this is a virtual numbers/tally table that is used to get all the days
between the days. If you already have a calendar table or a table that has
the dates you are querying this isn't necessary */
WITH E1(N)
AS (
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
), -- 1*10^1 or 10 rows
E2(N)
AS (
SELECT
1
FROM
E1 a,
E1 b
), -- 1*10^2 or 100 rows
E4(N)
AS (
SELECT
1
FROM
E2 a,
E2 b
), -- 1*10^4 or 10,000 rows
E8(N)
AS (
SELECT
1
FROM
E4 a,
E4 b
), -- 1*10^8 or 100,000,000 rows
nums
AS (
SELECT TOP (4000)
ROW_NUMBER() OVER (ORDER BY (
SELECT
NULL
)) - 1 AS N
FROM
E8
),
Calendar
AS (
SELECT
CONVERT(DATE, DATEADD(DAY, n, @StartDate)) AS theDate
FROM
nums
),
WeekDays
AS (
SELECT
*,
/* figure what day is the first day of the week. This setting is controlled by the
language of the SQL Server and you can see the values for DateFirst in sys.syslanguages */
CASE @@DateFirst
/* First day of week is monday (1) and last day of week is Sunday (7)*/
WHEN 1 THEN CASE DATEPART(WEEKDAY, theDate)
WHEN 7 THEN 0
ELSE DATEPART(WEEKDAY, theDate)
END
/* 1 and 7 are the only options for @@DATEFIRST currently so
Sunday is first day of week when @@DATEFIRS isn't 1 */
ELSE DATEPART(WEEKDAY, theDate) - 1
END AS DayNo,
DATENAME(WEEKDAY, theDate) AS DayName
FROM
Calendar
)
SELECT
*
FROM
WeekDays
WHERE
WeekDays.theDate BETWEEN @StartDate AND @EndDate AND
WeekDays.DayNo = @DayNo;

GO


DECLARE
@StartDate DATE = '2014-08-01',
@EndDate DATE = '2014-08-31',
@DayNo TINYINT = 6;

;
WITH cte_Recursion
AS (
SELECT
@startDate AS [Date]
UNION ALL
SELECT
DATEADD(DAY, 1, [Date])
FROM
cte_Recursion
WHERE
[Date] < @endDate
)
SELECT
[Date]
FROM
cte_Recursion
WHERE
DATEPART(WEEKDAY, [Date]) = @DayNo
OPTION
(MAXRECURSION 0)
--

SET STATISTICS IO OFF;

This is an interesting situation where, if you tune based on execution plan, the recursive cte looks better because if you run both in a batch the recursive cte solution says it's cost is 0% of the batch even though the top solution does 0 reads and the recursive cte does 187. The reason is that no matter how many rows you need to return the cost estimate for the recursive CTE remains the same.

For instance if you set the StartDate to 0001-08-01 and leave the EndDate as 2014-08-31 then the recursive CTE (on my laptop) takes ~6500 ms adn the virtual tally table solution takes ~900 ms.




Jack Corbett

Applications Developer

Don't let the good be the enemy of the best. -- Paul Fleming

Check out these links on how to get faster and more accurate answers:
Forum Etiquette: How to post data/code on a forum to get the best help
Need an Answer? Actually, No ... You Need a Question
How to Post Performance Problems
Crosstabs and Pivots or How to turn rows into columns Part 1
Crosstabs and Pivots or How to turn rows into columns Part 2
Post #1601269
Posted Friday, August 8, 2014 10:51 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Monday, November 24, 2014 7:37 AM
Points: 228, Visits: 568
Hi All,

Thank you so much. All solutions are suitable.


Thank yoy very much. :) :)

Thanks
Abhas.
Post #1601272
Posted Friday, August 8, 2014 10:56 AM
Hall of Fame

Hall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of FameHall of Fame

Group: General Forum Members
Last Login: Yesterday @ 10:36 PM
Points: 3,118, Visits: 11,555
Using the date table function on the link below, here are the queries you can use.

Date Table Function F_TABLE_DATE
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=61519


select
Sunday = [Date]
from
F_TABLE_DATE('08/01/2014','08/31/2014')
where
-- Select Sunday
ISO_DAY_OF_WEEK = 7

select
Monday = [Date]
from
F_TABLE_DATE('08/01/2014','08/31/2014')
where
-- Select Monday
ISO_DAY_OF_WEEK = 1


Results:

Sunday
-----------------------
2014-08-03 00:00:00.000
2014-08-10 00:00:00.000
2014-08-17 00:00:00.000
2014-08-24 00:00:00.000
2014-08-31 00:00:00.000

Monday
-----------------------
2014-08-04 00:00:00.000
2014-08-11 00:00:00.000
2014-08-18 00:00:00.000
2014-08-25 00:00:00.000





Post #1601275
Posted Friday, August 8, 2014 2:01 PM
SSCarpal Tunnel

SSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal TunnelSSCarpal Tunnel

Group: General Forum Members
Last Login: Tuesday, December 23, 2014 11:36 AM
Points: 4,625, Visits: 4,085
Jack's solution made me think of this:

declare @dtmStart datetime = '06/01/2014',
@dtmEnd datetime = '09/01/2014';

with dates_in_range(date_date, date_name) as (
select DATEADD(day, t.N - 1, @dtmStart), datename(weekday, DATEADD(day, t.N - 1, @dtmStart))
from dbo.Tally t
where t.N < DATEDIFF(day, @dtmStart, @dtmEnd) + 1)
select date_date, date_name
from dates_in_range
where date_name = 'Wednesday';

You need to have a tally table or use Itzik's approach like Jack did to do it. If you aren't familiar with Tally tables yet, check out the article in my signature. They'll change the way you look at data.



Tally Tables - Performance Personified
String Splitting with True Performance
Best practices on how to ask questions
Post #1601327
Posted Friday, August 8, 2014 2:57 PM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Yesterday @ 4:32 PM
Points: 6,879, Visits: 13,458
Expanding on Jacks solution, but eliminating the need to "hope" for @@DateFirst being either 1 or 0, here's an approach that's totally independent on the setting of @@DateFirst.
the biggest difference is the way to calculate DayNo:
DATEDIFF(dd,-1,theDate)%7 AS DayNo,
This code snippet is based on the fact that "day Zero" = 1900-01-01, which is a Monday.
The Modulo 7 will return the number of weekdays between 1900-01-01 an theDate, Zero, if theDate is a Monday and 6 if theDate is Sunday.
By shifting the day using -1 it'll start with Zero for Sunday to 6 for Saturday.

This code is also independent of any language setting (whereas Ed's solution for instance will fail if there's a SET LANGUAGE "GERMAN" is involved before his code).

@Jack and Ed: I'm sorry, but I'm a strong advocate against any form of non-deterministic date functions that'll rely on DATEFIRST and/or LANGUAGE settings. At least as long as there are alternatives available

DECLARE @StartDate DATE = '20140801', 
@EndDate DATE = '20140831',
@DayNo TINYINT = 0;

/* this is a virtual numbers/tally table that is used to get all the days
between the days. If you already have a calendar table or a table that has
the dates you are querying this isn't necessary */
WITH E1(N)
AS (
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
UNION ALL
SELECT
1
), -- 1*10^1 or 10 rows
E2(N)
AS (
SELECT
1
FROM
E1 a,
E1 b
), -- 1*10^2 or 100 rows
E4(N)
AS (
SELECT
1
FROM
E2 a,
E2 b
), -- 1*10^4 or 10,000 rows
E8(N)
AS (
SELECT
1
FROM
E4 a,
E4 b
), -- 1*10^8 or 100,000,000 rows
nums
AS (
SELECT TOP (4000)
ROW_NUMBER() OVER (ORDER BY (
SELECT
NULL
)) - 1 AS N
FROM
E8
),
Calendar
AS (
SELECT
CONVERT(DATE, DATEADD(DAY, n, @StartDate)) AS theDate
FROM
nums
),
WeekDays
AS (
SELECT
*,
DATEDIFF(dd,-1,theDate)%7 AS DayNo,
DATENAME(WEEKDAY, theDate) AS DayName
FROM
Calendar
)
SELECT
*
FROM
WeekDays
WHERE
WeekDays.theDate BETWEEN @StartDate
AND @EndDate AND
WeekDays.DayNo = @DayNo;





Lutz
A pessimist is an optimist with experience.

How to get fast answers to your question
How to post performance related questions
Links for Tally Table , Cross Tabs and Dynamic Cross Tabs , Delimited Split Function
Post #1601336
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse