SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

How to count Sundays between two dates?

Execute the following Microsoft SQL Server 2008 T-SQL scripts in Query Editor get a count of Sundays in the given date range.

datepart(dw,[Date]) = 1 indicates Sunday by default for US English language. DATE (date only without time, 3 bytes) data type is new to SQL Server 2008.

-- T-SQL find the count of Sundays in date range

-- Using spt_values to create a sequence (2506 rows)

USE AdventureWorks2008;

 

DECLARE  @StartDate DATE = '2012-01-01',

         @EndDate   DATE = '2013-06-01' 

 

SELECT Sundays = count(* )

FROM   (SELECT TOP ( datediff(DAY,@StartDate,@EndDate) + 1 )

                        [Date] = dateadd(DAY,ROW_NUMBER()

                  OVER(ORDER BY c1.name),

                  DATEADD(DD,-1,@StartDate))

        FROM   [master].[dbo].[spt_values] c1 ) x

WHERE  datepart(dw,[Date]) = 1;

/*

Sundays

74

*/

------------

 

-- T-SQL count Sunday using dynamically generated sequence

USE AdventureWorks2008;

DECLARE  @StartDate DATE = '2012-01-01',

         @EndDate   DATE = '2013-06-01' 

 

;WITH cteSequence ( SeqNo) as

(

      SELECTUNION ALL SELECT SeqNo + 1

      FROM cteSequence

      WHERE SeqNo < DATEDIFF(DD, @StartDate, @EndDate)+1

)

 

SELECT Sundays = count(* )

FROM   (SELECT TOP ( datediff(DAY,@StartDate,@EndDate) + 1 )

                        [Date] = dateadd(DAY,ROW_NUMBER()

                  OVER(ORDER BY c1.SeqNo),

                  DATEADD(DD,-1,@StartDate))

        FROM   cteSequence c1 ) x

WHERE  datepart(dw,[Date]) = 1

OPTION ( MAXRECURSION 0);

/*

Sundays

74

*/

------------

Related link: http://sqlusa.com/bestpractices/datetimeconversion/

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.