Archive

Posts Tagged ‘YTD’

YTD in SQL Query using Self-Join

May 22, 2009 Leave a comment

YTD - Abbreviation for YTD is Year-To-Date. YTD function will sum the measurable value from the period beginning January 1st of any year we specified up until the date we specified in the same year.

Database - “dbo.YTD

Table  Structure

DB Struc

Sample Records

dbo.YTD

SQL Query for YTD using Self-Join

/* Passing Date as a parameter*/
Declare @Date Datetime
Set @Date = ‘Mar 01, 08′
/* Calculating the Year beginning based on the Date parameter */
Declare @SDate Datetime
Set @SDate = Convert(Varchar, Convert(Datetime, @Date) – Datepart(y, Convert(Datetime, @Date)-1),7)
/* Converting the Date parameter to a generalized format */
Declare @EDate Datetime
Set @EDate = Convert(Varchar,(@Date),7)
/* Passing Product a parameter */
Declare @Product Nvarchar(25)
Set @Product = ‘AA’
/* Self-Join Query to display both YTD amount and the SaleAmount for a Particular Date in a single Query  */
Select A.ProductName, B.SalesAmount, Sum(A_sales) YTDSalesAmount
From

/* Query for calculating “YTD” */
(   Select ProductName, Sum(SalesAmount)as A_sales
From dbo.YTD
Where Date Between @SDate And @EDate AND ProductName = @Product
Group By ProductName    )A,
/* Query to show the “SalesAmount” for the “Date” Parameter*/
(   Select ProductName, SalesAmount
From dbo.YTD
Where Date = @EDate AND ProductName = @Product    )B

Group By A.ProductName, B.SalesAmount

Result

1. Date = ‘Mar 01, 08′ and Product =’AA’.

YTD Result AA

2. Date = ‘Mar 01, 08′ and Product =’AB.

YTD Result AB

Same like this by changing the “Date” Parameter, we can get YTD for different Dates.

Categories: SQL Server Tags:
Follow

Get every new post delivered to your Inbox.