0

我有一个基于选择的“结束日期”运行的查询。本质上,用户选择结束日期,查询将根据结束日期运行整个 YTD 的报告。因此,例如,如果我选择“12/3/12”,它应该从 1/1/12 - 12/3/12 运行报告。如果您在当天运行它,这将起作用......今天我尝试在结束日期“12/31/12”运行它但是我没有返回任何结果,因为我认为它试图根据今天的日期获取开始日期?以下是我的查询:

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
4

1 回答 1

4

GetDate()用参数替换@enddate它应该可以工作:

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

如果您查询:

declare @enddate datetime = '12/31/2012'

select DATEADD(yy, DATEDIFF(yy, 0, @enddate), 0)

它会返回2012-01-01你想要的。

于 2013-01-03T17:51:06.433 回答