我有一个基于所选“结束日期”运行的查询。用户基本上选择结束日期,查询将根据结束日期运行整个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
答案 0 :(得分: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
这就是你想要的。