Search code examples
sqldatetimesql-server-2000

How to run a query for year to date based on end date


I have a query that runs based on the "end date" picked. Essentially the user picks the end date, and the query will run the report for the entire YTD based on the end date. So for example if I select "12/3/12" it should run the report from 1/1/12 - 12/3/12. This works if you run it ON the day... Today I tried to run it for end date "12/31/12" however I return no results because I think it's trying to get the start date based on today's date? Below is my query:

SELECT        Store_Number, COUNT(DISTINCT Customer_Email_Address) AS Customer_email_address, COUNT(DISTINCT Invoice_Number) AS [Total Cars], 
                         @enddate AS End_Date, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AS Start_Date
FROM            Invoice_Tb
WHERE        (Invoice_Date BETWEEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND CONVERT(Datetime, @enddate, 102))
GROUP BY Store_Number

Solution

  • Replace the GetDate() with the @enddate parameter and it should work:

    SELECT        
        Store_Number, 
        COUNT(DISTINCT Customer_Email_Address) AS Customer_email_address, 
        COUNT(DISTINCT Invoice_Number) AS [Total Cars], 
        @enddate AS End_Date, 
        DATEADD(yy, DATEDIFF(yy, 0, @enddate), 0) AS Start_Date
    FROM Invoice_Tb
    WHERE (Invoice_Date BETWEEN DATEADD(yy, DATEDIFF(yy, 0, @enddate), 0) 
                        AND CONVERT(Datetime, @enddate, 102))
    GROUP BY Store_Number
    

    If you query:

    declare @enddate datetime = '12/31/2012'
    
    select DATEADD(yy, DATEDIFF(yy, 0, @enddate), 0)
    

    It will return 2012-01-01 which is what you want.