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 use the YEAR, MONTH and DAY functions?

Execute the following Microsoft SQL Server T-SQL scripts in SSMS Query Editor to demonstrate the application of Year, Month and Day datetime functions.

 

-- T-SQL Year, Month & Day functions

DECLARE @Date datetime = '2018-03-15'

 

-- SQL Server Year function

SELECT YYYY=YEAR(@Date)

SELECT YYYY=DATEPART(yy,@Date)

-- 2018

 

-- SQL Server Month function

SELECT MM=MONTH(@Date)

SELECT MM=DATEPART(mm,@Date)

-- 3

 

-- SQL Server Day function

SELECT DD=DAY(@Date)

SELECT DD=DATEPART(dd,@Date)

-- 15

 

-- YYYYMM aggregation

SELECT YYYYMM=CONVERT(varchar,year(OrderDate))+

       RIGHT('0'+CONVERT(varchar,month(OrderDate)),2),

       MonthlySales=SUM(TotalDue)

FROM AdventureWorks2008.Sales.SalesOrderHeader

WHERE YEAR(OrderDate)>2001

GROUP BY CONVERT(varchar,year(OrderDate))+

         RIGHT('0'+CONVERT(varchar,month(OrderDate)),2)

ORDER BY YYYYMM Desc

/*    YYYYMM      MonthlySales

      200407      56178.9223

      200406      6728034.9873

      200405      6518825.2262

      200404      4722890.7352

      200403      5272786.8106

      200402      5207182.5122

      200401      3691013.2227

*/

 

-- Alternative solution

SELECT YYYYMM=CONVERT(char(6),OrderDate,112),

       MonthlySales=SUM(TotalDue)

FROM AdventureWorks2008.Sales.SalesOrderHeader

WHERE YEAR(OrderDate)>2001

GROUP BY CONVERT(char(6),OrderDate,112)

ORDER BY YYYYMM Desc

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

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.